/**
* @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信任忽略所有证书
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...