170 lines
5.9 KiB
Java
170 lines
5.9 KiB
Java
package com.xiang.common.utils;
|
||
|
||
import cn.hutool.http.HttpRequest;
|
||
import com.xiang.common.handler.CallbackHandler;
|
||
import lombok.extern.slf4j.Slf4j;
|
||
import okhttp3.*;
|
||
|
||
import javax.net.ssl.*;
|
||
import java.io.IOException;
|
||
import java.net.InetSocketAddress;
|
||
import java.net.Proxy;
|
||
import java.security.KeyManagementException;
|
||
import java.security.NoSuchAlgorithmException;
|
||
import java.security.cert.CertificateException;
|
||
import java.security.cert.X509Certificate;
|
||
import java.util.Arrays;
|
||
import java.util.Map;
|
||
import java.util.concurrent.TimeUnit;
|
||
|
||
@Slf4j
|
||
public class OkHttpUtil {
|
||
|
||
private static final String secretId = "o82qrnb4z0s8y6j9qvyw";
|
||
private static final String signature = "p93f1o4fn6zht9sa6aryu9wpfp2el8dm";
|
||
private static final String urlString = "https://dps.kdlapi.com/api/getdps/?secret_id=" + secretId + "&signature=" + signature + "&num=1&format=text&sep=1";
|
||
// 用户名密码认证(私密代理/独享代理)
|
||
static final String username = "d2859987908";
|
||
static final String password = "1auxzpkz";
|
||
// 单例实例
|
||
private static final OkHttpUtil INSTANCE;
|
||
|
||
static {
|
||
try {
|
||
INSTANCE = new OkHttpUtil();
|
||
} catch (NoSuchAlgorithmException e) {
|
||
throw new RuntimeException(e);
|
||
} catch (KeyManagementException e) {
|
||
throw new RuntimeException(e);
|
||
}
|
||
}
|
||
|
||
// OkHttpClient 实例
|
||
private final OkHttpClient client;
|
||
|
||
// 私有构造方法,初始化 OkHttpClient
|
||
private OkHttpUtil() throws NoSuchAlgorithmException, KeyManagementException {
|
||
// 创建一个信任所有证书的TrustManager
|
||
final TrustManager[] trustAllCerts = new TrustManager[]{
|
||
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[]{};
|
||
}
|
||
}
|
||
};
|
||
// 初始化SSLContext
|
||
final SSLContext sslContext = SSLContext.getInstance("TLS");
|
||
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
|
||
|
||
// 创建一个信任所有主机名的HostnameVerifier
|
||
HostnameVerifier allHostsValid = new HostnameVerifier() {
|
||
@Override
|
||
public boolean verify(String hostname, SSLSession session) {
|
||
return true;
|
||
}
|
||
};
|
||
// 2. 配置连接池(关键参数)
|
||
ConnectionPool pool = new ConnectionPool(
|
||
5, // 最大空闲连接数(根据服务器承受能力调整)
|
||
5, // 存活时间(分钟)
|
||
TimeUnit.MINUTES
|
||
);
|
||
|
||
client = new OkHttpClient.Builder()
|
||
.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
|
||
.hostnameVerifier(allHostsValid)
|
||
.connectionPool(pool)
|
||
.connectTimeout(60, TimeUnit.SECONDS) // 连接超时时间
|
||
.readTimeout(60, TimeUnit.SECONDS) // 读取超时时间
|
||
.writeTimeout(60, TimeUnit.SECONDS) // 写入超时时间
|
||
.retryOnConnectionFailure(true) // 自动重试
|
||
.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)) // 协议优先级
|
||
.build();
|
||
}
|
||
|
||
public OkHttpUtil(OkHttpClient client){
|
||
this.client = client;
|
||
}
|
||
|
||
|
||
|
||
|
||
// 获取单例实例
|
||
public static OkHttpUtil getInstance() {
|
||
return INSTANCE;
|
||
}
|
||
|
||
|
||
/**
|
||
* 发送 GET 请求
|
||
*
|
||
* @param url 请求URL
|
||
* @param headers 请求头(可以为空)
|
||
* @return 响应结果
|
||
* @throws IOException 请求失败时抛出异常
|
||
*/
|
||
public String get(String url, Map<String, String> headers) throws IOException {
|
||
Request.Builder builder = new Request.Builder().url(url);
|
||
|
||
// 添加请求头
|
||
if (headers != null) {
|
||
for (Map.Entry<String, String> entry : headers.entrySet()) {
|
||
builder.addHeader(entry.getKey(), entry.getValue());
|
||
}
|
||
}
|
||
|
||
Request request = builder.build();
|
||
try (Response response = client.newCall(request).execute()) {
|
||
String string = response.body().string();
|
||
if (!response.isSuccessful()) {
|
||
log.error("{}okhttp请求失败: {}-->", url, string);
|
||
}
|
||
return string;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 发送 POST 请求(JSON 格式)
|
||
*
|
||
* @param url 请求URL
|
||
* @param headers 请求头(可以为空)
|
||
* @param json JSON 请求体
|
||
* @return 响应结果
|
||
* @throws IOException 请求失败时抛出异常
|
||
*/
|
||
public String postJson(String url, Map<String, String> headers, String json) throws IOException {
|
||
RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
|
||
Request.Builder builder = new Request.Builder()
|
||
.url(url)
|
||
.post(body)
|
||
.addHeader("User-Agent", "BookingClient/1.0");
|
||
|
||
// 添加请求头
|
||
if (headers != null) {
|
||
for (Map.Entry<String, String> entry : headers.entrySet()) {
|
||
builder.addHeader(entry.getKey(), entry.getValue());
|
||
}
|
||
}
|
||
|
||
Request request = builder.build();
|
||
|
||
try (Response response = client.newCall(request).execute()) {
|
||
String string = response.body().string();
|
||
if (!response.isSuccessful()) {
|
||
log.error("{}okhttp请求失败: {}-->", url, string);
|
||
return string;
|
||
}
|
||
return string;
|
||
}
|
||
}
|
||
}
|