https構建(基礎)

tony0087發表於2021-09-09

先寫最基礎的,你才能學框架聯網等,

public class HttpUtils {

    public interface HttpListener {
        void onSuccess(String content);

        void onFail(Exception ex);
    }

    private static Handler mUIHandler = new Handler(Looper.getMainLooper());

    public static void doGet(final Context context, final String urlStr, final HttpListener listener) {
        new Thread() {
            @Override
            public void run() {

                InputStream is = null;
                try {
                    URL url = new URL(urlStr);

                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

                    SSLContext sslContext = SSLContext.getInstance("TLS");//協議

                    X509Certificate serverCert = getCert(context);
                    TrustManager[] trustManagers = {new MyX509TrustManager(serverCert)};
                    sslContext.init(null, trustManagers, new SecureRandom());//三種,第二個是陣列我們要信任那些證照
                    conn.setSSLSocketFactory(sslContext.getSocketFactory());
                    //對域名的效驗
                    conn.setHostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            HostnameVerifier defaultHostnameVerifier
                                    = HttpsURLConnection.getDefaultHostnameVerifier();
                            return defaultHostnameVerifier.verify("kyfw.12306.cn", session);
                        }
                    });
                    //以上是htpps需要的
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(5000);
                    conn.setConnectTimeout(5000);
                    conn.connect();

                    is = conn.getInputStream();
                    InputStreamReader isr = new InputStreamReader(is);//char對應是Reader如果用byte用Stream就行
                    char[] buf = new char[2048];
                    int len = -1;
                    final StringBuilder content = new StringBuilder();
                    while ((len = isr.read(buf)) != -1) {
                        content.append(new String(buf, 0, len));
                    }

                    mUIHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onSuccess(content.toString());
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                    listener.onFail(e);
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        }.start();
    }

    /**
     * 獲取證照判斷證照
     * @param context
     * @return
     */
    private static X509Certificate getCert(Context context) {

        try {
            InputStream is = context.getAssets().open("srca.cer");
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");//建立證照
            return (X509Certificate) certificateFactory.generateCertificate(is);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        }

        return null;
    }

}
/**
 * 檢查證照
 */
public class MyX509TrustManager implements X509TrustManager {

    private X509Certificate mServerCert;//證照

    public MyX509TrustManager(X509Certificate certificate) {
        mServerCert = certificate;
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//判斷證照合法性
        for (X509Certificate certificate : chain) {

            // 證照是否過期以及合法性的校驗
            certificate.checkValidity();
            try {
                certificate.verify(mServerCert.getPublicKey());//傳入公鑰
            } catch (Exception e) {
                throw new CertificateException(e);
            }

        }

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}
有這個你就可以了,下面第二方法
public class HttpUtils2 {

    public interface HttpListener {
        void onSuccess(String content);

        void onFail(Exception ex);
    }

    private static Handler mUIHandler = new Handler(Looper.getMainLooper());

    public static void doGet(final Context context, final String urlStr, final HttpListener listener) {
        new Thread() {
            @Override
            public void run() {

                InputStream is = null;
                try {
                    URL url = new URL(urlStr);

                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    X509Certificate serverCert = getCert(context);
                    //
                    String keyStoreType = KeyStore.getDefaultType();
                    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
                    keyStore.load(null);
                    keyStore.setCertificateEntry("srca",serverCert);

                    TrustManagerFactory trustManagerFactory =
                            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    trustManagerFactory.init(keyStore);
                    //
                    SSLContext sslContext = SSLContext.getInstance("TLS");
                    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
                    sslContext.init(null, trustManagers, new SecureRandom());
                    conn.setSSLSocketFactory(sslContext.getSocketFactory());

                    conn.setHostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            HostnameVerifier defaultHostnameVerifier
                                    = HttpsURLConnection.getDefaultHostnameVerifier();
                            return defaultHostnameVerifier.verify("kyfw.12306.cn", session);
                        }
                    });

                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(5000);
                    conn.setConnectTimeout(5000);
                    conn.connect();

                    is = conn.getInputStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    char[] buf = new char[2048];
                    int len = -1;
                    final StringBuilder content = new StringBuilder();
                    while ((len = isr.read(buf)) != -1) {
                        content.append(new String(buf, 0, len));
                    }

                    mUIHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onSuccess(content.toString());
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                    listener.onFail(e);
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        }.start();
    }

    private static X509Certificate getCert(Context context) {

        try {
            InputStream is = context.getAssets().open("srca.cer");
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            return (X509Certificate) certificateFactory.generateCertificate(is);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        }

        return null;
    }

}
這就是最基礎的東西了

原文連結:http://www.apkbus.com/blog-340477-76561.html

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/1747/viewspace-2813061/,如需轉載,請註明出處,否則將追究法律責任。

相關文章