okHttp3请求https信任忽略所有证书

/**

* @descprition post+json方式工具方法

* @param url:请求地址 , json:请求数据 

* @return java.lang.String

* @date 2020-05-13

* @version 1.0 

*/

public static String sendByPostJson(String url, String json) {

    // 如果不需要忽略证书可new OkHttpClient();实现自己的业务

    OkHttpClient client =getUnsafeOkHttpClient();

    //10秒连接超时
    client.newBuilder().connectTimeout(3, TimeUnit.SECONDS)
     //10m秒写入超时
     .writeTimeout(10, TimeUnit.SECONDS)
     //10秒读取超时
    .readTimeout(10, TimeUnit.SECONDS) .build();

    RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);

    Request request =new Request.Builder().url(url).post(body).build();

    try {

        Response response = client.newCall(request).execute();

        assert response.body() !=null;

        return response.body().string();

    }catch (IOException e) {

        e.printStackTrace();

    }

    return null;

}


/**

* okHttp3添加信任所有证书

* @return

*/

public static OkHttpClientgetUnsafeOkHttpClient() {

try {

    final TrustManager[] trustAllCerts =new TrustManager[]{

    new X509TrustManager() {

    @Override

                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {

    }

    @Override

                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {

    }

    @Override

                    public java.security.cert.X509Certificate[]getAcceptedIssuers() {

                        return new java.security.cert.X509Certificate[]{};

                    }

    }

};

        final SSLContext sslContext = SSLContext.getInstance("TLS");

        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient.Builder builder =new OkHttpClient.Builder();

        // builder.sslSocketFactory(sslSocketFactory )方法已过时,使用下面方法替代

        builder.sslSocketFactory(sslSocketFactory,(X509TrustManager)trustAllCerts[0]);

        builder.hostnameVerifier(new HostnameVerifier() {

// 可以将不需要忽略的域名放入数组,也可为空(忽略所有证书)

String[]arr =new String[]{};

            @Override

            public boolean verify(String hostname, SSLSession session) {

if (TextUtils.isEmpty(hostname)) {

return false;

                }

return !Arrays.asList(arr).contains(hostname);

            }

});

        return builder.build();

    }catch (Exception e) {

throw new RuntimeException(e);

    }

}

你可能感兴趣的:(okHttp3请求https信任忽略所有证书)