整理了一下HttpClient发送HTTP/HTTPS的GET/POST请求工具类。
导包
org.apache.httpcomponents
httpclient
4.5.6
【java|HttpClient发送HTTP/HTTPS的GET/POST请求工具类(绕过证书验证)】直接贴代码
package com.icbc.cxlab.common.utils.scaffold;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* http工具类
*/
public class HttpClientUtils {private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class);
/**
* 发送http+get请求
* @param url
* @return 返回结果
* @throws Exception
*/
public static String sendHttpGet(String url) throws Exception {CloseableHttpClient httpClient = HttpClients.createDefault();
return doGet(url,httpClient);
}/**
* 发送https+get请求,绕过证书
* @param url 请求地址
* @return 返回结果
* @throws Exception
*/
public static String sendHttpsGet(String url) throws Exception {CloseableHttpClient httpClient = createIgnoreVerifyHttpClient();
//CloseableHttpClient httpClient = HttpClients.createDefault();
return doGet(url,httpClient);
}/**
* 发送http+post请求
* @param url 请求地址
* @param params 请求参数 json字符串
* @return 返回结果
* @throws Exception
*/
public static String sendHttpPost(String url, String params) throws Exception {CloseableHttpClient httpClient = HttpClients.createDefault();
return doPost(httpClient, url, params);
}/**
* 发送https+post请求
* @param url 请求地址
* @param params 请求参数 json字符串
* @return 返回结果
* @throws Exception
*/
public static String sendHttpsPost(String url, String params) throws Exception {CloseableHttpClient httpClient = createIgnoreVerifyHttpClient();
//CloseableHttpClient httpClient = HttpClients.createDefault();
return doPost(httpClient, url, params);
}/**
* 封装get请求方式的处理
*/
private static String doGet(String url,CloseableHttpClient httpClient) throws Exception {log.info("HGet请求url={}", url);
HttpGet httpGet = new HttpGet(url);
return execute(httpClient,httpGet);
}/**
* 封装post请求方式的处理
*/
private static String doPost(CloseableHttpClient httpClient, String url, String params) throws Exception {log.info("Post请求url:{}", url);
log.info("Post请求params:{}", params);
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;
charset=utf-8");
httpPost.setEntity(new StringEntity(params));
return execute(httpClient,httpPost);
}/**
* 执行发送
*/
private static String execute(CloseableHttpClient httpClient, HttpRequestBase requestBase) throws Exception {String result = null;
CloseableHttpResponse response = null;
try {response = httpClient.execute(requestBase);
int statusCode = response.getStatusLine().getStatusCode();
log.info("HttpClient响应码={}", statusCode);
if (statusCode == 200) {result = EntityUtils.toString(response.getEntity(),"utf-8");
} else {log.error("HttpClient请求失败,错误码={}", statusCode);
}
} catch (Exception e) {log.error("HttpClient请求异常:", e);
} finally {if (null != httpClient) {httpClient.close();
}
if (null != response) {response.close();
}
}
log.info("HttpClient请求结果:{}", result);
return result;
}/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static CloseableHttpClient createIgnoreVerifyHttpClient() throws Exception {SSLContext sslContext = SSLContext.getInstance("TLS");
// 实现一个X509TrustManager接口
X509TrustManager trustManager = new X509TrustManager() {@Override
public void checkClientTrusted(
X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {}@Override
public void checkServerTrusted(
X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {}@Override
public X509Certificate[] getAcceptedIssuers() {return null;
}
};
sslContext.init(null, new TrustManager[]{
trustManager}, null);
Registry socketFactoryRegistry =
RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext)).build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
return httpClient;
}}
推荐阅读
- 牛客网|【Java刷题进阶】基础入门篇⑤
- java|关于微信小程序与Java后台交互数据中中文乱码问题的讨论
- 网易二面(Kafka为什么吞吐量大、速度快(?))
- JEECG低代码平台|JeecgBoot 3.4.0 版本发布,微服务重构版本
- 别再乱打日志了,这份 Java 日志规范,应有尽有,建议收藏!!
- mall学习教程|Mall电商实战项目微服务版本全面升级,支持最新版SpringCloud,权限解决方案升级...
- 小程序|继微信支付后 支付宝宣布向银联云闪付开放线上场景
- 【docker专栏8】使用IDEA远程管理docker镜像及容器服务
- QuickFIX|QuickFix Java 讲解(四)服务器的搭建与解析