- pom
okhttp 目前最新的版本已经 5.x了
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
- yml
okhttp:
connect-timeout: 60
read-timeout: 60
write-timeout: 60
max-idle-connections: 200 # 连接池中整体的空闲连接的最大数量
keep-alive-duration: 300 # 连接空闲时间最多为 300 秒
- Config
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
@Configuration
public class OkHttpConfig {
@Value("${okhttp.connect-timeout}")
private Integer connectTimeout;
@Value("${okhttp.read-timeout}")
private Integer readTimeout;
@Value("${okhttp.write-timeout}")
private Integer writeTimeout;
@Value("${okhttp.max-idle-connections}")
private Integer maxIdleConnections;
@Value("${okhttp.keep-alive-duration}")
private Long keepAliveDuration;
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory(), x509TrustManager())
// 是否开启缓存
.retryOnConnectionFailure(false)
.connectionPool(pool())
.connectTimeout(connectTimeout, TimeUnit.SECONDS)
.readTimeout(readTimeout, TimeUnit.SECONDS)
.writeTimeout(writeTimeout, TimeUnit.SECONDS)
.hostnameVerifier((hostname, session) -> true)
// 设置代理
// .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)))
// 拦截器
// .addInterceptor()
.build();
}
@Bean
public X509TrustManager x509TrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
}
/*
@Bean
public SSLSocketFactory sslSocketFactory() {
String certPath = "";
String caPath = "";
String certPwd = "";
String caPwd = "";
try {
ClassPathResource selfcertPath = new ClassPathResource(certPath);
ClassPathResource trustcaPath = new ClassPathResource(caPath);
KeyStore selfCert = KeyStore.getInstance("pkcs12");
selfCert.load(selfcertPath.getInputStream(), certPwd.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509");
kmf.init(selfCert, certPwd.toCharArray());
KeyStore caCert = KeyStore.getInstance("jks");
caCert.load(trustcaPath.getInputStream(), caPwd.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509");
tmf.init(caCert);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return sslContext.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
*/
@Bean
public SSLSocketFactory sslSocketFactory() {
try {
TrustManager[] trustManagers = new TrustManager[]{x509TrustManager()};
// 信任任何链接
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, new SecureRandom());
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
return null;
}
@Bean
public ConnectionPool pool() {
return new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS);
}
}
- Util
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Component
public class OkHttpUtil {
public static final MediaType JSON = MediaType.Companion.parse("application/json; charset=utf-8");
public static final MediaType XML = MediaType.parse("application/xml; charset=utf-8");
public static final MediaType FORM = MediaType.get("application/x-www-form-urlencoded; charset=utf-8");
@Autowired
private OkHttpClient okHttpClient;
public Response doGet(String url, Map<String, String> params, String[] headers) throws IOException {
StringBuilder sb = new StringBuilder(url);
if (!ObjectUtils.isEmpty(params)) {
boolean firstFlag = true;
for (String key : params.keySet()) {
if (firstFlag) {
sb.append("?").append(key).append("=").append(params.get(key));
firstFlag = false;
} else {
sb.append("&").append(key).append("=").append(params.get(key));
}
}
}
Request.Builder builder = new Request.Builder();
if (!ObjectUtils.isEmpty(headers) && headers.length % 2 == 0) {
for (int i = 0; i < headers.length; i = i + 2) {
builder.addHeader(headers[i], headers[i + 1]);
}
}
Request request = builder
.url(sb.toString())
.build();
Call call = okHttpClient.newCall(request);
Response response = call.execute();
return response;
}
public Response doPost(String url, Map<String, String> params) throws IOException {
FormBody.Builder builder = new FormBody.Builder();
if (!ObjectUtils.isEmpty(params)) {
for (String key : params.keySet()) {
builder.add(key, params.get(key));
}
}
Request request = new Request.Builder()
.url(url)
.post(builder.build())
.build();
Call call = okHttpClient.newCall(request);
Response response = call.execute();
return response;
}
public Response doPost(String url, String data, MediaType contentType) throws IOException {
RequestBody requestBody = RequestBody.create(data, contentType);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
//.method("POST", requestBody)
.build();
Call call = okHttpClient.newCall(request);
Response response = call.execute();
return response;
}
}
网友评论