HttpClient5

package com.springboot.springboottest.utils;

import org.apache.hc.client5.http.config.RequestConfig;
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.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

public class HttpClientConfig {
    private HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    private static final Timeout connectTimeout = Timeout.ofSeconds(10);
    private static final Timeout requestTimeout = Timeout.ofSeconds(30);

    public static HttpClientConfig custom() {
        return new HttpClientConfig();
    }

    public CloseableHttpClient build() {
        //兼容http以及https请求
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", initSSlFactory())
                .build();
        //适配http以及https请求 通过new创建PoolingHttpClientConnectionManager
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        //https请求 通过PoolingHttpClientConnectionManagerBuilder直级创建
//        PoolingHttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create()
//                .setSSLSocketFactory(initSSlFactory())
//                .setValidateAfterInactivity(TimeValue.ofSeconds(10))
//                .setMaxConnPerRoute(maxConnTotal - 1)
//                .setMaxConnTotal(maxConnTotal)
//                .build();

        httpClientBuilder.setConnectionManager(connManager).evictExpiredConnections().evictIdleConnections(TimeValue.ofSeconds(5)).disableAutomaticRetries();
        httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
                .setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(requestTimeout)
                .build());
        return httpClientBuilder.build();
    }

    private static SSLConnectionSocketFactory initSSlFactory() {
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{}, null);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
        return new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
    }
}
package com.springboot.springboottest.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.ToString;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.io.ManagedHttpClientConnectionFactory;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpUtils {

    public static CloseableHttpClient httpClient = HttpClientConfig.custom().build();

    public static <T> HttpResponse<T> httpJsonPost(String url, Map<String, String> headers, Object data, Class<T> tClass) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        StringEntity s = new StringEntity(data instanceof String ? (String) data : JSONObject.toJSONString(data)
                , ContentType.APPLICATION_JSON);
        httpPost.setEntity(s);
        return executeHttp(tClass, httpPost);
    }


    private static <T> HttpResponse<T> executeHttp(Class<T> tClass, ClassicHttpRequest request) throws IOException, ParseException {
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            int code = response.getCode();
            String reasonPhrase = response.getReasonPhrase();
            HttpResponse<T> responseData = new HttpResponse<>();
            responseData.setRetCode(code);
            responseData.setRetMsg(reasonPhrase);
            if (code >= HttpStatus.SC_SUCCESS && code < HttpStatus.SC_REDIRECTION) {
                String data = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                if (tClass.isAssignableFrom(String.class)) {
                    responseData.setData((T) data);
                } else {
                    responseData.setData(JSONObject.parseObject(data, tClass));
                }
            }
            EntityUtils.consume(response.getEntity());
            return responseData;
        }
    }

    @Data
    @ToString
    static class HttpResponse<T> {
        int retCode;
        String retMsg;
        T data;
    }
}
//www.greatytc.com/p/1ec57f6428b7
https://blog.csdn.net/weixin_39355187/article/details/124277094
https://blog.csdn.net/shenbururen/article/details/115483590
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 神经网络 sigmod函数和softmax函数最大似然概率和交叉熵和多类别交叉熵Logistic回归和梯度下降...
    左心Chris阅读 847评论 0 0
  • 计算机网络 网络基础 计算机网络基础知识总结[https://mp.weixin.qq.com/s/WfcozFA...
    White7阅读 539评论 0 2
  • 算法题 https://github.com/afatcoder/LeetcodeTop[https://gith...
    帝王鲨kingcp阅读 885评论 0 0
  • “面试,有一定的技巧在里边,但是更重要的在于平时的积累。” —— 美团面试官的一句话。“临阵磨枪可以让你找到一...
    春田花花幼儿园阅读 1,321评论 4 29
  • 原文链接链接://www.greatytc.com/p/6be91ee932a7[https://www...
    Small_Cake阅读 17,730评论 18 207