java httpClientUtil


import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClientConnectionManager;
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.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.core.type.TypeReference;

import java.io.IOException;
import java.nio.charset.UnsupportedCharsetException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

public class HttpClientUtil {

    private static final String CHARSET = "UTF-8";

    private static HttpClientConnectionManager httpClientConnectionManager;
    private static HttpClientBuilder httpClientBuilder;
    private static CloseableHttpClient httpClient;

    /**
     * 初始化http连接管理器.
     */
    private static void initHttpClientConnectionManager() {

        final TrustStrategy trustStrategy = (chain, authType) -> true;

        SSLConnectionSocketFactory sslConnectionSocketFactory = null;
        try {
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(trustStrategy).build());
        } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslConnectionSocketFactory).build();
        httpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
    }

    /**
     * 初始化httpclient创建工厂.
     */
    private static void initHttpClientBuilder() {
        httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(httpClientConnectionManager);
    }

    /**
     * 得到httpClient
     */
    private static CloseableHttpClient newHttpClient() {

        if (httpClient == null) {
            if (httpClientBuilder == null) {
                if (httpClientConnectionManager == null) {
                    initHttpClientConnectionManager();
                }
                initHttpClientBuilder();
            }
            httpClient = httpClientBuilder.build();
        }
        return httpClient;
    }

    /**
     * Post请求(传递cookie).
     *
     * @param url
     * @param headerParams 请求头参数
     * @param params
     * @param retType      带泛型返回参数
     * @return
     */
    public static <T> T doPost(String url, Map<String, String> headerParams, Object params, TypeReference<T> retType) {

        T respObj = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;

        if (StringUtils.isBlank(url)) {
            return respObj;
        }
        if (retType == null) {
            return respObj;
        }
        try {
            httpPost = new HttpPost(url);
            // 构建请求头
            if (headerParams != null) {
                buildHttpReqHeader(httpPost, headerParams);
            }
            /**
             * 1.填充参数. 2.发送. 3.解析返回值
             */
            httpPost.setEntity(buildPostParam(params));
            response = newHttpClient().execute(httpPost);
            respObj = handlePostResponse(url, response, retType);

            // 释放response响应
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return respObj;
    }

    /**
     * 构建HTTP请求头.
     *
     * @param requestBase
     * @param headerParams
     */
    private static void buildHttpReqHeader(HttpRequestBase requestBase, Map<String, String> headerParams) {
        for (String headerKey : headerParams.keySet()) {
            requestBase.addHeader(headerKey, headerParams.get(headerKey));
        }
    }

    /**
     * 构建Post请求参数
     *
     * @return
     * @throws Exception
     */
    private static HttpEntity buildPostParam(Object param) throws Exception {
        StringEntity entity;
        try {
            if (param instanceof String) {
                entity = new StringEntity(param.toString(), CHARSET);
            } else {
                entity = new StringEntity(JsonUtils.toJson(param), CHARSET);
            }
        } catch (UnsupportedCharsetException e) {
            e.printStackTrace();
            throw e;
        }
        entity.setContentEncoding(CHARSET);
        entity.setContentType("application/json");

        return entity;
    }

    /**
     * 处理post响应结果
     *
     * @param url
     * @param response
     * @param retType
     * @return
     */
    private static <T> T handlePostResponse(String url, CloseableHttpResponse response, TypeReference<T> retType) {
        HttpEntity entity;
        String respString;

        try {
            entity = response.getEntity();
            if (entity != null) {
                respString = EntityUtils.toString(entity, CHARSET);
                if (!StringUtils.isBlank(respString)) {
                    return JsonUtils.toBean(respString, retType);
                }
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值