引入相关依赖包
<!--okhttp依赖包-->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
<!--lombok用于简化实体类开发-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
跳过证书配置类代码
package com.xz.https;
import okhttp3.OkHttpClient;
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;
/**
* @Description 跳过证书配置类
* @author xz
*/
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[]{};
}
}
};
}
}
okhttp方式的 https工具类代码
package com.xz.https;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @Description okhttp方式的 https工具类
* @author xz
*/
@Slf4j
public class OkhttpsUtils {
/**
* 获取客户端链接
*/
private static OkHttpClient getClient() {
OkHttpClient okHttpClient = OKHttpClientBuilder.buildOKHttpClient().
connectTimeout(5000, TimeUnit.SECONDS).
readTimeout(20000, TimeUnit.SECONDS).
writeTimeout(20000, TimeUnit.SECONDS).
build();
return okHttpClient;
}
private static Request getRequest(String url, Map<String,String> header) throws MalformedURLException {
Request.Builder builder = getBuilder(header);
URL uri = new URL(url);
return builder.url(uri).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);
}
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 {
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 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);
}
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;
}
}
测试代码
package com.xz.https;
import com.alibaba.fastjson.JSONObject;
/**
* @author: xz
* @since: 2024/1/11 22:07
* @description:
*/
public class HttpsUtilsTest {
public static void main(String[] args) throws Exception {
String url="https://xxx.com.cn:5678/gateway/user/service/getxxxx";
UserReq userReq = new UserReq ();
userReq .setName("张三");
String result = OkhttpsUtils.doPost(url, JSONObject.toJSONString(accessTokenReq), null);
System.out.println("Okhttps---https请求:"+result);
}
}