okHttp工具类
一、导入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.4</version>
</dependency>
二、HttpClientConfig配置类
public class HttpClientConfig {
private String masterUrl;
private boolean trustCerts;
private String username;
private String password;
private int connectionTimeout;
private int requestTimeout;
private int websocketPingInterval;
private int maxConcurrentRequestsPerHost;
private int maxConnection;
private String httpProxy;
private String httpsProxy;
private String proxyUsername;
private String proxyPassword;
private String userAgent;
private TlsVersion[] tlsVersions = new TlsVersion[]{TLS_1_2};
private String[] noProxy;
public static final String HTTP_PROTOCOL_PREFIX = "http://";
public static final String HTTPS_PROTOCOL_PREFIX = "https://";
}
三、HttpClientUtils工具类
package com.yolo.springbootzkeco.util;
import cn.hutool.json.JSONUtil;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import static okhttp3.ConnectionSpec.CLEARTEXT;
public class HttpClientUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
private static final Map<String, OkHttpClient> map_clients = new ConcurrentHashMap<>();
private static OkHttpClient okHttpClient2;
private HttpClientUtils() {
}
private static OkHttpClient getInstance(final HttpClientConfig config) {
if (map_clients.containsKey(md5Key(config))) {
return map_clients.get(md5Key(config));
}
OkHttpClient okHttpClient = createHttpClient(config);
map_clients.put(md5Key(config), okHttpClient);
return okHttpClient;
}
private static OkHttpClient getOkHttpClient(HttpClientConfig config) {
if (okHttpClient2 == null) {
okHttpClient2 = createHttpClient(config);
}
return okHttpClient2;
}
private static String md5Key(HttpClientConfig config) {
return getMD5InHex( config.getMasterUrl() + "/" + config.getUsername() + "/" + config.getPassword() + "/");
}
private static String getMD5InHex(String data) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(data.getBytes());
byte[] result = messageDigest.digest();
return new BigInteger(1, result).toString(16);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
private static OkHttpClient createHttpClient(final HttpClientConfig config) {
try {
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
httpClientBuilder.followRedirects(true);
httpClientBuilder.followSslRedirects(true);
if (config.isTrustCerts()) {
httpClientBuilder.hostnameVerifier((s, sslSession) -> true);
}
TrustManager[] trustManagers = buildTrustManagers();
httpClientBuilder.sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0]);
if (config.getConnectionTimeout() > 0) {
httpClientBuilder.connectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
}
if (config.getRequestTimeout() > 0) {
httpClientBuilder.readTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
}
if (config.getWebsocketPingInterval() > 0) {
httpClientBuilder.pingInterval(config.getWebsocketPingInterval(), TimeUnit.MILLISECONDS);
}
if (config.getMaxConcurrentRequestsPerHost() > 0) {
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequestsPerHost(config.getMaxConcurrentRequestsPerHost());
httpClientBuilder.dispatcher(dispatcher);
}
if (config.getMaxConnection() > 0) {
ConnectionPool connectionPool = new ConnectionPool(config.getMaxConnection(), 60, TimeUnit.SECONDS);
httpClientBuilder.connectionPool(connectionPool);
}
if (config.getMasterUrl().toLowerCase().startsWith(HttpClientConfig.HTTP_PROTOCOL_PREFIX) || config.getMasterUrl().startsWith(HttpClientConfig.HTTPS_PROTOCOL_PREFIX)) {
try {
URL proxyUrl = getProxyUrl(config);
if (proxyUrl != null) {
httpClientBuilder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
if (config.getProxyUsername() != null) {
httpClientBuilder.proxyAuthenticator((route, response) -> {
String credential = Credentials.basic(config.getProxyUsername(), config.getProxyPassword());
return response.request().newBuilder().header("Proxy-Authorization", credential).build();
});
}
}
} catch (MalformedURLException e) {
throw new RuntimeException("Invalid proxy server configuration", e);
}
}
if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
httpClientBuilder.addNetworkInterceptor(chain -> {
Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent()).build();
return chain.proceed(agent);
});
}
if (config.getTlsVersions() != null && config.getTlsVersions().length > 0) {
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(config.getTlsVersions())
.build();
httpClientBuilder.connectionSpecs(Arrays.asList(spec, CLEARTEXT));
}
return httpClientBuilder.build();
} catch (Exception e) {
throw new RuntimeException("创建OKHTTPClient错误", e);
}
}
private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
return ssfFactory;
}
private static TrustManager[] buildTrustManagers() {
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[]{};
}
}
};
}
private static URL getProxyUrl(HttpClientConfig config) throws MalformedURLException {
URL master = new URL(config.getMasterUrl());
String host = master.getHost();
if (config.getNoProxy() != null) {
for (String noProxy : config.getNoProxy()) {
if (host.endsWith(noProxy)) {
return null;
}
}
}
String proxy = config.getHttpsProxy();
if (master.getProtocol().equals("http")) {
proxy = config.getHttpProxy();
}
if (proxy != null) {
return new URL(proxy);
}
return null;
}
public static String doPost(boolean isJsonPost,HttpClientConfig httpClientConfig,Map<String,String> paramMap){
Response response = null;
try {
OkHttpClient client = getInstance(httpClientConfig);
RequestBody requestBody;
if (isJsonPost){
String json = "";
if (paramMap != null) {
json = JSONUtil.toJsonStr(paramMap);
}
requestBody = RequestBody.create(MediaType.parse("application/json"), json);
}else {
FormBody.Builder formBody = new FormBody.Builder();
if (paramMap != null) {
paramMap.forEach(formBody::add);
}
requestBody = formBody.build();
}
Request.Builder builder = new Request.Builder();
Request request = builder.url(httpClientConfig.getMasterUrl()).post(requestBody).build();
response = client.newCall(request).execute();
if (response.isSuccessful() && response.body() != null) {
return response.body().string();
} else if (response.body() != null){
logger.info(response.body().string());
return null;
}
} catch (IOException e){
e.printStackTrace();
} finally {
if (response != null){
response.close();
}
}
return null;
}
public static String doPost(HttpClientConfig httpClientConfig, Map<String,Object> map){
Response response = null;
try {
OkHttpClient client = getInstance(httpClientConfig);
String json = "";
if (map != null) {
json = JSONUtil.toJsonStr(map);
System.out.println(json);
}
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
Request.Builder builder = new Request.Builder();
Request request = builder.url(httpClientConfig.getMasterUrl()).post(requestBody).build();
response = client.newCall(request).execute();
if (response.isSuccessful() && response.body() != null) {
return response.body().string();
} else if (response.body() != null){
logger.info(response.body().string());
return null;
}
} catch (IOException e){
e.printStackTrace();
} finally {
if (response != null){
response.close();
}
}
return null;
}
public static String doPostByToken(boolean isJsonPost,HttpClientConfig httpClientConfig, Map<String,String> paramMap, String token){
Response response = null;
try {
OkHttpClient client = getInstance(httpClientConfig);
RequestBody requestBody;
if (isJsonPost){
String json = "";
if (paramMap != null) {
json = JSONUtil.toJsonStr(paramMap);
}
requestBody = RequestBody.create(MediaType.parse("application/json"), json);
}else {
FormBody.Builder formBody = new FormBody.Builder();
if (paramMap != null) {
paramMap.forEach(formBody::add);
}
requestBody = formBody.build();
}
Request.Builder builder = new Request.Builder();
Request request = builder.url(httpClientConfig.getMasterUrl()).header("Authorization", token).post(requestBody).build();
response = client.newCall(request).execute();
if (response.isSuccessful() && response.body() != null) {
return response.body().string();
} else if (response.body() != null){
logger.info(response.body().string());
return null;
}
} catch (IOException e){
e.printStackTrace();
} finally {
if (response != null){
response.close();
}
}
return null;
}
public static Headers doLoginRequest(boolean isJsonPost,HttpClientConfig config, Map<String, String> paramMap) {
Response response = null;
try {
OkHttpClient client = getInstance(config);
RequestBody requestBody;
if (isJsonPost){
String json = "";
if (paramMap != null) {
json = JSONUtil.toJsonStr(paramMap);
}
requestBody = RequestBody.create(MediaType.parse("application/json"), json);
}else {
FormBody.Builder formBody = new FormBody.Builder();
if (paramMap != null) {
paramMap.forEach(formBody::add);
}
requestBody = formBody.build();
}
Request request = new Request.Builder().url(config.getMasterUrl()).post(requestBody).build();
response = client.newCall(request).execute();
if (response.isSuccessful() && response.body() != null) {
return response.headers();
} else if (response.body() != null){
return null;
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (response != null){
response.close();
}
}
return null;
}
}