继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

https构建(基础)

繁花不似锦
关注TA
已关注
手记 337
粉丝 50
获赞 241

先写最基础的,你才能学框架联网等,

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

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP