封装:
package gj.okhttp3;
import okhttp3.OkHttpClient;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
/**
* Author: areful
* Date: 2019/2/15
*/
public class OKHttpClientBuilder {
public static OkHttpClient.Builder buildOKHttpClient() {
try {
TrustManager[] trustAllCerts = buildTrustManagers();
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier((hostname, session) -> true);
return builder;
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
return new OkHttpClient.Builder();
}
}
private static TrustManager[] buildTrustManagers() {
return 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[]{};
}
}
};
}
}
测试:
package gj.okhttp3;
import okhttp3.*;
import java.io.IOException;
import java.util.HashMap;
/**
* Author: areful
* Date: 2019/2/15
*/
public class TestOKHttpClientBuilder {
public static void main(String[] args) {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String url = "https://www.baidu.com";
String json = "{}";
Request request = new Request.Builder()
.url(url)
.headers(Headers.of(new HashMap<>()))
.post(RequestBody.create(JSON, json))
.build();
OKHttpClientBuilder.buildOKHttpClient()
.build()
.newCall(request)
.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("onFailure()");
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) {
System.out.println("onResponse()");
}
});
}
}