https网络请求,添加证书

Retrofit +RxJava

用OkHttps:

String cert = CERT_PROD;
        /*证书*/
        InputStream[] inputStream = new InputStream[]{new Buffer().writeUtf8(cert).inputStream()};//证书
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(inputStream, null, null);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }).sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
        /*证书 end*/
        builder.connectTimeout(HTTP_CONNECTION_TIME_OUT, TimeUnit.SECONDS).
                readTimeout(HTTP_READ_TIME_OUT, TimeUnit.SECONDS);

用HttpsURLConnection:

HostnameVerifier hv = new HostnameVerifier() {
                    public boolean verify(String urlHostName, SSLSession session) {
                        LogUtil.e(TAG, "Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                        return true;
                    }
                };
                HttpsURLConnection.setDefaultHostnameVerifier(hv);
                conn = (HttpsURLConnection) new URL(info.realUrl).openConnection();
                addSSL(conn);
…

private void addSSL(HttpsURLConnection conn) {
        SSLSocketFactory factory = getSSlSocketFactory();
        conn.setSSLSocketFactory(factory);
    }

    private SSLSocketFactory getSSlSocketFactory() {
        String cert = CERT_PROD;
        /*证书*/
        InputStream[] inputStream = new InputStream[]{new Buffer().writeUtf8(cert).inputStream()};//证书
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(inputStream, null, null);
        return sslParams.sSLSocketFactory;
        /*证书 end*/
    }

猜你喜欢

转载自blog.csdn.net/T_yoo_csdn/article/details/83302479