一、说明
就是一个工具类,使用了httpclient5-fluent流式组件,其实单纯用这个组件已经很方便了。只是有一些配置要自定义,所以再封装一层。
注释懒得加了,看参数名应该就明白了。有哪里不对的欢迎指正。
二、maven引用
- 这里流式组件已经依赖了 httpclient5了,所以不需要再单独引用。
- hutool工具包太好用了,我所有项目都会引用。hutool里也有httputil,只是不支持连接池。
<dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5-fluent</artifactId> <version>5.0.3</version> </dependency> <!-- 小而全的Java工具类库 --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.5.9</version> </dependency>
三、工具类
- 去掉了https证书验证
- 禁用了请求重试
disableAutomaticRetries()
- 简单的post、get、上传文件 等封装。有需要其他的可以自行调用call 方法。
- 可自行调整连接池大小和超时时间。
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.fluent.Form;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.client5.http.fluent.Response;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.HttpEntities;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedTrustManager;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Map;
/**
* @author sun
* @date 2021-02-25
**/
public class HttpUtil {
private static final int maxConnTotal = 200;
private static final Timeout connectTimeout = Timeout.ofSeconds(10);
private static final Timeout requestTimeout = Timeout.ofSeconds(30);
public static String uploadFile(String urlString, Map<String, Object> paramMap) throws Exception {
return uploadFile(urlString, null, paramMap, CharsetUtil.CHARSET_UTF_8)
.returnContent()
.asString(CharsetUtil.CHARSET_UTF_8);
}
public static String uploadFile(String urlString, Map<String, Object> paramMap, Charset charSet) throws Exception {
return uploadFile(urlString, null, paramMap, charSet)
.returnContent()
.asString(charSet);
}
public static Response uploadFile(String urlString, Map<String, Object> handlerMap, Map<String, Object> paramMap) throws Exception {
return uploadFile(urlString, handlerMap, paramMap, CharsetUtil.CHARSET_UTF_8);
}
public static Response uploadFile(String urlString, Map<String, Object> handlerMap, Map<String, Object> paramMap, Charset charSet) throws Exception {
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(charSet);
paramMap.forEach((k, v) -> {
//判断是文件还是文本
if (v instanceof File) {
File file = (File) v;
builder.addBinaryBody(k, file, ContentType.MULTIPART_FORM_DATA.withCharset(charSet), FileUtil.getName(file));
} else {
builder.addTextBody(k, v.toString(), ContentType.TEXT_PLAIN.withCharset(charSet));
}
});
Request request = Request.post(urlString)
.body(builder.build());
//添加消息头
if (CollUtil.isNotEmpty(handlerMap)) {
handlerMap.forEach((k, v) -> request.addHeader(k, v.toString()));
}
return call(request);
}
public static String post(String urlString, Map<String, Object> paramMap) throws Exception {
return post(urlString, paramMap, CharsetUtil.CHARSET_UTF_8);
}
public static String post(String urlString, Map<String, Object> paramMap, Charset charSet) throws Exception {
return post(urlString, null, paramMap, charSet)
.returnContent()
.asString(charSet);
}
public static Response post(String urlString, Map<String, Object> handlerMap, Map<String, Object> paramMap) throws Exception {
return post(urlString, handlerMap, paramMap, CharsetUtil.CHARSET_UTF_8);
}
public static Response post(String urlString, Map<String, Object> handlerMap, Map<String, Object> paramMap, Charset charSet) throws Exception {
Form form = Form.form();
if (CollUtil.isNotEmpty(paramMap)) {
paramMap.forEach((k, v) -> form.add(k, v.toString()));
}
Request request = Request.post(urlString)
.bodyForm(form.build(), charSet);
//添加消息头
if (CollUtil.isNotEmpty(handlerMap)) {
handlerMap.forEach((k, v) -> request.addHeader(k, v.toString()));
}
return call(request);
}
public static String post(String urlString, String body) throws IOException {
return post(urlString, body, CharsetUtil.CHARSET_UTF_8);
}
public static String post(String urlString, String body, Charset charSet) throws IOException {
return post(urlString, null, body, charSet)
.returnContent()
.asString(charSet);
}
public static Response post(String urlString, Map<String, Object> handlerMap, String body) throws IOException {
return post(urlString, handlerMap, body, CharsetUtil.CHARSET_UTF_8);
}
public static Response post(String urlString, Map<String, Object> handlerMap, String body, Charset charSet) throws IOException {
HttpEntity httpEntity = HttpEntities.create(body, getContentType(body, charSet));
Request request = Request.post(urlString)
.body(httpEntity);
//添加消息头
if (CollUtil.isNotEmpty(handlerMap)) {
handlerMap.forEach((k, v) -> request.addHeader(k, v.toString()));
}
return call(request);
}
public static String get(String urlString) throws Exception {
return get(urlString, null, CharsetUtil.CHARSET_UTF_8);
}
public static String get(String urlString, Map<String, Object> paramMap) throws Exception {
return get(urlString, paramMap, CharsetUtil.CHARSET_UTF_8);
}
public static String get(String urlString, Map<String, Object> paramMap, Charset charSet) throws Exception {
return get(urlString, null, paramMap, charSet)
.returnContent()
.asString(charSet);
}
public static String get(String urlString, Map<String, Object> handlerMap, Map<String, Object> paramMap) throws Exception {
return get(urlString, handlerMap, paramMap, CharsetUtil.CHARSET_UTF_8)
.returnContent()
.asString(CharsetUtil.CHARSET_UTF_8);
}
public static Response get(String urlString, Map<String, Object> handlerMap, Map<String, Object> paramMap, Charset charSet) throws Exception {
Form form = Form.form();
if (CollUtil.isNotEmpty(paramMap)) {
paramMap.forEach((k, v) -> form.add(k, v.toString()));
}
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(form.build(), charSet));
Request request = Request.get(urlString + '?' + paramStr);
//添加消息头
if (CollUtil.isNotEmpty(handlerMap)) {
handlerMap.forEach((k, v) -> request.addHeader(k, v.toString()));
}
return call(request);
}
public static Response call(Request request) throws IOException {
return request.execute(Client.c);
}
public static ContentType getContentType(String body, Charset charSet) {
ContentType contentType = ContentType.TEXT_PLAIN;
if (StrUtil.isNotBlank(body)) {
char firstChar = body.charAt(0);
switch (firstChar) {
case '{':
case '[':
// JSON请求体
contentType = ContentType.APPLICATION_JSON;
break;
case '<':
// XML请求体
contentType = ContentType.APPLICATION_XML;
break;
default:
break;
}
}
if (charSet != null) {
contentType.withCharset(charSet);
}
return contentType;
}
private static class Client {
private static final CloseableHttpClient c = HttpClientBuilder.create()
.setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(getSSLFactory())
.setValidateAfterInactivity(TimeValue.ofSeconds(10))
.setMaxConnPerRoute(maxConnTotal - 1)
.setMaxConnTotal(maxConnTotal)
.build())
.evictIdleConnections(TimeValue.ofMinutes(1))
.disableAutomaticRetries()
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(requestTimeout)
.build())
.build();
private static SSLConnectionSocketFactory getSSLFactory() {
X509ExtendedTrustManager trustManager = new X509ExtendedTrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) {
}
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) {
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{trustManager}, null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
assert ctx != null;
return new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
}
}
}