1.自定义配置类(详解//TODO)
@Configuration
public class OkHttpConfiguration {
@Bean
public OkHttpClient myHttpClient() {
return new OkHttpClient.Builder().sslSocketFactory(getSSLSocketFactory(),getX509TrustManager())
.hostnameVerifier(getHostnameVerifier())
.retryOnConnectionFailure(Boolean.TRUE)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30,TimeUnit.SECONDS)
.build();
}
// 获取SSLSocketFactory
public static SSLSocketFactory getSSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, getTrustManager(), new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 获取TrustManager
private static TrustManager[] getTrustManager() {
return new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
};
}
// 获取HostnameVerifier
public static HostnameVerifier getHostnameVerifier() {
return (s, sslSession) -> true;
}
public static X509TrustManager getX509TrustManager() {
X509TrustManager trustManager = null;
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
trustManager = (X509TrustManager) trustManagers[0];
} catch (Exception e) {
e.printStackTrace();
}
return trustManager;
}
}
2.使用
@Component
public class OkHttpUtils {
@Qualifier("myHttpClient")
private OkHttpClient okHttpClient;
// post请求
public String postJsonParams(String url, String jsonParams) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
return this.doHttp(request);
}
// get请求
public String getJsonParams(String url) {
Request request = new Request.Builder()
.url(url)
.get()
.build();
return this.doHttp(request);
}
public String doHttp(Request request) {
Response response = null;
String result = null;
try {
response = okHttpClient.newCall(request).execute();
result = response.body().string();
} catch (Exception e) {
log.error(e.getMessage());
}finally {
if (response != null) {
response.close();
}
}
return result;
}
}