1、添加POM依赖
<!-- okhttp3 依赖 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
2、NOCAS配置:
ok:
http:
connect-timeout: 60
read-timeout: 60
write-timeout: 60
# 连接池中整体的空闲连接的最大数量
max-idle-connections: 200
# 连接空闲时间最多为 300 秒
keep-alive-duration: 300
3、config配置
import lombok.extern.slf4j.Slf4j;
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 java.util.concurrent.TimeUnit;
@Slf4j
@Configuration
public class OkHttpConfig {
@Value("${ok.http.connect-timeout}")
private int connectTimeout;
@Value("${ok.http.read-timeout}")
private int readTimeout;
@Value("${ok.http.write-timeout}")
private int writeTimeout;
@Value("${ok.http.max-idle-connections}")
private int maxIdleConnections;
@Value("${ok.http.keep-alive-duration}")
private int keepAliveDuration;
@Bean public
OkHttpClient okHttpClient() {
log.info("connectTimeout: [{}] readTimeout: [{}] writeTimeout: [{}]", connectTimeout, readTimeout, writeTimeout);
log.info("maxIdleConnections: [{}] keepAliveDuration: [{}]", maxIdleConnections, keepAliveDuration);
// 创建连接池
ConnectionPool connectionPool = new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS);
// 使用配置初始化
OkHttpClient OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(connectTimeout, TimeUnit.SECONDS)
.readTimeout(readTimeout, TimeUnit.SECONDS)
.writeTimeout(writeTimeout, TimeUnit.SECONDS)
.connectionPool(connectionPool)
.build();
log.info("OkHttp 配置完成");
return client;
}
}
4、封装Util
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.time.LocalDateTime;
import java.util.Map;
@Slf4j
@Component
public class OkHttpUtils {
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
@Autowired
private OkHttpClient okHttpClient;
/** * 发送POST请求,包含token、signature和参数
* @param token 认证Token
* @param xSignature 签名
* @param paramMap 请求参数
* @param url 请求URL
* @return 响应体中的字符串
* @throws IOException 网络请求异常
*/
public String postJson(String url, String token, String xSignature, Map<String, Object> paramMap) throws IOException {
log.info("【postJson】请求开始时间: {} 入参url: {} token: {} xSignature: {} paramMap: {}", LocalDateTime.now(), url, token, xSignature, paramMap);
JSONObject jsonParam = new JSONObject(paramMap);
RequestBody requestBody = RequestBody.create(JSON, jsonParam.toString());
Request request = new Request.Builder()
.header(ACCEPT, APPLICATION_JSON)
.header(CONTENT_TYPE, APPLICATION_JSON)
.header(AUTHORIZATION, BEARER + SPACE + token)
.header(X_SIGNATURE, xSignature)
.url(url)
.post(requestBody)
.build();
try (Response response = okHttpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
log.error("【postJson】{} error message: {}", url, response);
throw new IOException("Unexpected code " + response);
}
return response.body().string();
}
finally {
log.info("【postJson】{}请求结束时间: {}", url, LocalDateTime.now()); }
}
}