项目场景:
项目场景:客户要求使用https的网址,导致项目里各种接口都要是https的,但是实施大部分都不会导入证书这些操作,故需要调整为代码能绕过证书直接访问https接口。
问题描述
使用代码直接请求htts接口时,会抛出异常:
javax.net.ssl.SSLPeerUnverifiedException: Hostname 39.175.165.121 not verified:
certificate: sha1/nHCdaKjuohTDcm+CkfN0L3fS0Yk=
DN: CN=*.txdbkj.cn
subjectAltNames: [*.txdbkj.cn, txdbkj.cn]
at com.squareup.okhttp.internal.io.RealConnection.connectTls(RealConnection.java:201)
at com.squareup.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:149)
at com.squareup.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
at com.squareup.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
at com.squareup.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.squareup.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
解决方案:
先创建跳过证书工具类
/**
* 绕过https证书的类
*
* @author: lihl
* @date: 2024/8/16 下午5:17
*/
public class OKHttpClientBuilder {
public static OkHttpClient.Builder buildOKHttpClient() {
try {
TrustManager[] trustAllCerts = buildTrustManagers();
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier((hostname, session) -> true);
return builder;
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
return new OkHttpClient.Builder();
}
}
private static TrustManager[] buildTrustManagers() {
return new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
}
}
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @author: lihl
* @date: 2024/8/16 下午5:39
*/
@Slf4j
public class OkhttpsUtils {
/**
* 获取客户端链接
*/
private static OkHttpClient getClient() {
OkHttpClient okHttpClient = OKHttpClientBuilder.buildOKHttpClient().
connectTimeout(60000, TimeUnit.SECONDS).
readTimeout(60000, TimeUnit.SECONDS).
writeTimeout(60000, TimeUnit.SECONDS).
build();
return okHttpClient;
}
private static Request getRequest(String url, Map<String,String> header) throws MalformedURLException {
Request.Builder builder = getBuilder(header);
return builder.url(url).build();
}
private static Request.Builder getBuilder(Map<String,String> header) {
Request.Builder builder = new Request.Builder();
builder.addHeader("accept", "application/json").
addHeader("connection", "Keep-Alive").
addHeader("Content-Type", "application/json;charset=UTF-8");
if(header != null && header.entrySet().size()>0){
for(Map.Entry<String,String> entry:header.entrySet()){
builder.addHeader(entry.getKey(),entry.getValue());
}
}
return builder;
}
/**
* doGet请求
*/
public static String doGet(String url, String param, Map<String,String> header) {
if (param != null) {
url = url + "?" + param;
}
String result = null;
try {
OkHttpClient okHttpClient = getClient();
Request request = getRequest(url,header);
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
result = body.string();
} else {
throw new IOException("response body is null");
}
} else {
response.close();
}
} catch (IOException e) {
log.error("GET请求异常,url = {}", url, e);
throw new RuntimeException("GET请求异常,url = "+ url+";"+e.getMessage());
}
return result;
}
public static Response doGetResponst(String url, String param, Map<String,String> header) {
if (param != null) {
url = url + "?" + param;
}
Response result = null;
try {
OkHttpClient okHttpClient = getClient();
Request request = getRequest(url,header);
Response response = okHttpClient.newCall(request).execute();
} catch (IOException e) {
log.error("GET请求异常,url = {}", url, e);
throw new RuntimeException("GET请求异常,url = "+ url+";"+e.getMessage());
}
return result;
}
/**
* doPost请求
*/
public static String doPost(String url, String param,Map<String,String> header) {
OkHttpClient okHttpClient = getClient();
Request.Builder builder = getBuilder(header);
String result = null;
try {
MediaType mediaType = MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE);
if (header != null && !StringUtils.isEmpty(header.get("Content-Type"))){
mediaType = MediaType.parse(header.get("Content-Type") );
}
RequestBody requestBody = RequestBody.create(param.getBytes("UTF-8"),
mediaType);
builder.post(requestBody);
Request request = builder.url(url).build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
result = body.string();
} else {
throw new IOException("response body is null");
}
} else {
response.close();
}
} catch (Exception e) {
log.error("POST请求异常,url = {}", url, e);
throw new RuntimeException("POST请求异常,url = "+ url+";"+e.getMessage());
}
return result;
}
/**
* doDelete请求
*/
public static String doDelete(String url, String param,Map<String,String> header) {
OkHttpClient okHttpClient = getClient();
Request.Builder builder = getBuilder(header);
String result = null;
try {
if (param != null) {
RequestBody requestBody = RequestBody.create(param.getBytes("UTF-8"),
MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE));
builder.delete(requestBody);
} else {
builder.delete();
}
Request request = builder.url(url).build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
result = body.string();
} else {
throw new IOException("response body is null");
}
} else {
response.close();
}
} catch (Exception e) {
log.error("DELETE请求异常,url = {}", url, e);
}
return result;
}
/**
* doPut请求
*/
public static String doPut(String url, String param,Map<String,String> header) {
OkHttpClient okHttpClient = getClient();
Request.Builder builder = getBuilder(header);
String result = null;
try {
RequestBody requestBody = RequestBody.create(param.getBytes("UTF-8"),
MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE));
builder.put(requestBody);
Request request = builder.url(url).build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
result = body.string();
} else {
throw new IOException("response body is null");
}
} else {
response.close();
}
} catch (Exception e) {
log.error("PUT请求异常,url = {}", url, e);
}
return result;
}
/**
* doPost请求
*/
public static Response doPostResponse(String url, String param,Map<String,String> header) {
Response response = null;
OkHttpClient okHttpClient = getClient();
Request.Builder builder = getBuilder(header);
try {
RequestBody requestBody = RequestBody.create(param.getBytes("UTF-8"),
MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE));
builder.post(requestBody);
Request request = builder.url(url).build();
response = okHttpClient.newCall(request).execute();
} catch (Exception e) {
log.error("POST请求异常,url = {}", url, e);
throw new RuntimeException("POST请求异常,url = "+url + "异常信息:"+e.getMessage());
}
return response;
}
}
使用方式:
public String get(String path, Map<String, String> header) throws IOException {
logger.info(path);
String content = OkhttpsUtils.doGet(path,null,header);
return content;
}
public String postJson(String url, String json, Map<String, String> header){
logger.info("url={}", url);
logger.info("header={}", header);
logger.info("body={}", json);
json = json == null ? "" : json;
String res = OkhttpsUtils.doPost(url, json,header);
return res;
}