java工具类HttpUtil,支持http和https(忽略Certification)
开发过程中,将springboot应用改为https请求后,普通的http请求会报错,原因是卡在证书认证了,添加了忽略认证的请求方式。
import java.util.Map;
import okhttp3.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.alibaba.fastjson.JSON;
import okhttp3.FormBody.Builder;
public class HttpUtil {
static final Logger logger = LogManager.getLogger(HttpUtil.class.getName());
/**
* post请求
* @param url url
* @param data postData
* @return response.body().string()
*/
public static String post(String url, Map<String, Object> data) {
OkHttpClient httpClient = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.get("application/json"), JSON.toJSONString(data));
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = null;
try {
Call call = httpClient.newCall(request);
response = call.execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
// TODO: handle exception
logger.error(e.getMessage());
}finally {
if (response != null) {
response.body().close();
response.close();
}
}
return null;
}
/**
* put请求
* @param url url
* @param data putData
* @return response.body().string()
*/
public static String put(String url, Map<String, Object> data) {
OkHttpClient httpClient = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.get("application/json"), JSON.toJSONString(data));
Request request = new Request.Builder().url(url).method("PUT", requestBody).build();
Response response = null;
try {
Call call = httpClient.newCall(request);
response = call.execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
// TODO: handle exception
logger.error(e.getMessage());
}finally {
if (response != null) {
response.body().close();
response.close();
}
}
return null;
}
/**
* post表单请求
* @param url url
* @param data postData
* @return response.body().string()
*/
public static String formPost(String url, Map<String, String> data) {
OkHttpClient httpClient = new OkHttpClient();
Builder builder = new FormBody.Builder();
for (String key : data.keySet()) {
builder.add(key, data.get(key));
}
Request request = new Request.Builder().url(url).post(builder.build()).build();
Response response = null;
try {
Call call = httpClient.newCall(request);
response = call.execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
// TODO: handle exception
logger.error(e.getMessage());
}finally {
if (response != null) {
response.body().close();
response.close();
}
}
return null;
}
/**
* get请求
* @param url url
* @return response.body().string()
*/
public static String get(String url) {
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = null;
try {
response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
if (response != null) {
response.body().close();
response.close();
}
}
return null;
}
/**
* get请求忽略ssl认证
* @param url url
* @return response.body().string()
*/
public static String getIgnoreCertification(String url) {
Request request = new Request.Builder().url(url).build();
Response response = null;
try {
response = OKHttpClientBuilder.buildOKHttpClient()
.build()
.newCall(request)
.execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
if (response != null) {
response.body().close();
response.close();
}
}
return null;
}
/**
* post请求忽略ssl认证
* @param url url
* @param data postData
* @return response.body().string()
*/
public static String postIgnoreCertification(String url, Map<String, Object> data) {
RequestBody requestBody = RequestBody.create(MediaType.get("application/json"), JSON.toJSONString(data));
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = null;
try {
response = OKHttpClientBuilder.buildOKHttpClient()
.build()
.newCall(request)
.execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
// TODO: handle exception
logger.error(e.getMessage());
}finally {
if (response != null) {
response.body().close();
response.close();
}
}
return null;
}
}
OKHttpClientBuilder类
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: https请求忽略认证
* @Author: wangzg
* @Time: 2021/8/26
*/
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[]{};
}
}
};
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗