Httpclient5工具类

一、说明

就是一个工具类,使用了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.ContentBody;
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.ParseException;
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 void main(String[] args) throws Exception {
	}

	public static String uploadFile(String urlString, Map<String, Object> paramMap) throws IOException {
		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 IOException {
		return uploadFile(urlString, null, paramMap, charSet)
				.returnContent()
				.asString(charSet);
	}

	public static Response uploadFile(String urlString, Map<String, Object> headerMap, Map<String, Object> paramMap) throws IOException {
		return uploadFile(urlString, headerMap, paramMap, CharsetUtil.CHARSET_UTF_8);
	}

	public static Response uploadFile(String urlString, Map<String, Object> headerMap, Map<String, Object> paramMap, Charset charSet) throws IOException {
		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 if (v instanceof ContentBody) {
				builder.addPart(k, (ContentBody) v);
			} else {
				builder.addTextBody(k, String.valueOf(v), ContentType.TEXT_PLAIN.withCharset(charSet));
			}
		});
		Request request = Request.post(urlString)
				.body(builder.build());
		//添加消息头
		if (CollUtil.isNotEmpty(headerMap)) {
			headerMap.forEach((k, v) -> request.addHeader(k, String.valueOf(v)));
		}
		return call(request);
	}

	public static String post(String urlString, Map<String, Object> paramMap) throws IOException {
		return post(urlString, paramMap, CharsetUtil.CHARSET_UTF_8);
	}

	public static String post(String urlString, Map<String, Object> paramMap, Charset charSet) throws IOException {
		return post(urlString, null, paramMap, charSet)
				.returnContent()
				.asString(charSet);
	}

	public static Response post(String urlString, Map<String, Object> headerMap, Map<String, Object> paramMap) throws IOException {
		return post(urlString, headerMap, paramMap, CharsetUtil.CHARSET_UTF_8);
	}

	public static Response post(String urlString, Map<String, Object> headerMap, Map<String, Object> paramMap, Charset charSet) throws IOException {
		Form form = Form.form();
		if (CollUtil.isNotEmpty(paramMap)) {
			paramMap.forEach((k, v) -> form.add(k, String.valueOf(v)));
		}
		Request request = Request.post(urlString)
				.bodyForm(form.build(), charSet);
		//添加消息头
		if (CollUtil.isNotEmpty(headerMap)) {
			headerMap.forEach((k, v) -> request.addHeader(k, String.valueOf(v)));
		}
		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> headerMap, String body) throws IOException {
		return post(urlString, headerMap, body, CharsetUtil.CHARSET_UTF_8);
	}

	public static Response post(String urlString, Map<String, Object> headerMap, String body, Charset charSet) throws IOException {
		HttpEntity httpEntity = HttpEntities.create(body, getContentType(body, charSet));
		Request request = Request.post(urlString)
				.body(httpEntity);
		//添加消息头
		if (CollUtil.isNotEmpty(headerMap)) {
			headerMap.forEach((k, v) -> request.addHeader(k, String.valueOf(v)));
		}
		return call(request);
	}

	public static String get(String urlString) throws IOException, ParseException {
		return get(urlString, null, CharsetUtil.CHARSET_UTF_8);
	}

	public static String get(String urlString, Map<String, Object> paramMap) throws IOException, ParseException {
		return get(urlString, paramMap, CharsetUtil.CHARSET_UTF_8);
	}

	public static String get(String urlString, Map<String, Object> paramMap, Charset charSet) throws IOException, ParseException {
		return get(urlString, null, paramMap, charSet)
				.returnContent()
				.asString(charSet);
	}

	public static String get(String urlString, Map<String, Object> headerMap, Map<String, Object> paramMap) throws IOException, ParseException {
		return get(urlString, headerMap, paramMap, CharsetUtil.CHARSET_UTF_8)
				.returnContent()
				.asString(CharsetUtil.CHARSET_UTF_8);
	}

	public static Response get(String urlString, Map<String, Object> headerMap, Map<String, Object> paramMap, Charset charSet) throws IOException, ParseException {
		Form form = Form.form();
		if (CollUtil.isNotEmpty(paramMap)) {
			paramMap.forEach((k, v) -> form.add(k, String.valueOf(v)));
		}
		String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(form.build(), charSet));
		Request request = Request.get(urlString + '?' + paramStr);
		//添加消息头
		if (CollUtil.isNotEmpty(headerMap)) {
			headerMap.forEach((k, v) -> request.addHeader(k, String.valueOf(v)));
		}
		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);
		}
	}
}

 

 

 

 

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值