提交 13a2b3cd authored 作者: 姜武杰's avatar 姜武杰

使用okhttp进行重写,okhttp自己控制池化

上级 0639e7f7
...@@ -357,6 +357,10 @@ ...@@ -357,6 +357,10 @@
<groupId>com.msl.message</groupId> <groupId>com.msl.message</groupId>
<artifactId>message-sdk</artifactId> <artifactId>message-sdk</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
</dependencies> </dependencies>
......
package com.openapi.sdk.util; package com.openapi.sdk.util;
import javax.net.ssl.*; import okhttp3.*;
import java.io.DataOutputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.security.KeyManagementException;
import java.net.HttpURLConnection; import java.security.NoSuchAlgorithmException;
import java.net.URL;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
public class HttpsUtils { public class HttpsUtils {
public HttpsUtils() {
}
public static String doPost(String url, int connentTimeout, int readTimeout) throws Exception { private static final OkHttpClient client;
HttpURLConnection conn = null;
InputStreamReader isReader = null;
StringBuffer result = new StringBuffer();
static {
try { try {
trustAllHttpsCertificates(); // 创建一个信任所有证书的 TrustManager
HostnameVerifier hv = new HostnameVerifier() { TrustManager[] trustAllCerts = new TrustManager[]{
public boolean verify(String urlHostName, SSLSession session) { new X509TrustManager() {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); @Override
return true; public void checkClientTrusted(X509Certificate[] chain, String authType) {
} }
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}; };
HttpsURLConnection.setDefaultHostnameVerifier(hv);
conn = (HttpURLConnection)(new URL(url)).openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setConnectTimeout(connentTimeout);
conn.setReadTimeout(readTimeout);
isReader = new InputStreamReader(conn.getInputStream(), "UTF-8");
char[] bfchar = new char[2048];
int length = 0;
while((length = isReader.read(bfchar)) != -1) {
String temp = new String(bfchar, 0, length);
result.append(temp);
}
} catch (Exception var17) {
System.err.println("发送 POST 请求出现异常!" + var17.getMessage());
throw var17;
} finally {
try {
if (isReader != null) {
isReader.close();
}
} catch (IOException var16) {
System.err.println("关闭数据流出错了!\n" + var16.getMessage() + "\n");
throw var16;
}
}
return result.toString(); // 安装所有信任的 SSL 套接字工厂
} SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new SecureRandom());
public static String doPost(String url, String param, int readTimeout, int connectTimeout) throws Exception { // 创建一个允许所有主机名的 HostnameVerifier
InputStreamReader isReader = null; HostnameVerifier hostnameVerifier = (hostname, session) -> {
HttpURLConnection conn = null; System.out.println("Warning: URL Host: " + hostname + " vs. " + session.getPeerHost());
DataOutputStream dos = null; return true;
StringBuffer result = new StringBuffer();
try {
trustAllHttpsCertificates();
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
}; };
HttpsURLConnection.setDefaultHostnameVerifier(hv);
conn = (HttpURLConnection)(new URL(url)).openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Length", String.valueOf(param.getBytes("UTF-8").length));
conn.setRequestMethod("POST");
conn.setConnectTimeout(connectTimeout);
conn.setRequestProperty("charset", "UTF-8");
conn.setReadTimeout(readTimeout);
conn.connect();
dos = new DataOutputStream(conn.getOutputStream());
int length = 0;
int totalLength = param.length();
while(length < totalLength) {
int endLength = length + 1024;
if (endLength > totalLength) {
endLength = totalLength;
}
dos.write(param.substring(length, endLength).getBytes("UTF-8"));
length = endLength;
dos.flush();
}
dos.close();
isReader = new InputStreamReader(conn.getInputStream(), "UTF-8");
char[] bfchar = new char[2048];
int rlength = 0;
while((rlength = isReader.read(bfchar)) != -1) {
String temp = new String(bfchar, 0, rlength);
result.append(temp);
}
return result.toString();
} catch (Exception var21) {
System.err.println("发送 POST 请求出现异常!" + var21.getMessage() + "e:" + var21);
throw var21;
} finally {
try {
if (isReader != null) {
isReader.close();
}
} catch (IOException var20) {
System.err.println("关闭数据流出错了!\n" + var20.getMessage() + "\n");
throw var20;
}
try {
if (conn != null) {
conn.disconnect();
}
} catch (Exception var19) {
System.err.println("关闭连接出错了!\n" + var19.getMessage() + "\n");
throw var19;
}
// 创建 OkHttpClient 并启用连接池
client = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
.hostnameVerifier(hostnameVerifier)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException("Failed to create OkHttpClient", e);
} }
} }
private static void trustAllHttpsCertificates() throws Exception { public static String doPost(String url, int connectTimeout, int readTimeout) throws IOException {
TrustManager[] trustAllCerts = new TrustManager[1]; Request request = new Request.Builder()
TrustManager tm = new miTM(); .url(url)
trustAllCerts[0] = tm; .post(RequestBody.create("", MediaType.get("application/x-www-form-urlencoded")))
SSLContext sc = SSLContext.getInstance("SSL"); .build();
sc.init((KeyManager[])null, trustAllCerts, (SecureRandom)null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager, X509TrustManager {
miTM() {
}
public X509Certificate[] getAcceptedIssuers() { try (Response response = client.newCall(request).execute()) {
return null; if (!response.isSuccessful()) {
} throw new IOException("Unexpected code " + response);
}
public boolean isServerTrusted(X509Certificate[] certs) { return response.body().string();
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
} }
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { public static String doPost(String url, String param, int readTimeout, int connectTimeout) throws IOException {
} RequestBody body = RequestBody.create(param, MediaType.get("application/x-www-form-urlencoded"));
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
return response.body().string();
} }
} }
} }
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论