编码技巧——HTTPClient工具类

开发中,系统之间调用方式,存在部分老接口(RPC框架如DUBBO出现之前),如HTTP接口;因此我们需要自己写HTTP客户端来调用接口,传入url、请求方式、参数,获取HTTPResponse;

下面给2个HTTPclient的示例,分别是以前在不同项目写过的,便于开发时便捷使用:

(1)第一种(刚入职写的,做一个httpclient3.x到4.5的升级)

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
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.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author AA
 * @description 基于httpclient4.5的httpclient工具类
 * @date 2019/12/2
 */
@Slf4j
public class HttpClientUtil {
    /**
     * 配置缓存
     */
    private static final Map<String, Object> props;

    /**
     * http连接池
     */
    private static final PoolingHttpClientConnectionManager manager;

    /**
     * client
     */
    private static final CloseableHttpClient client;

    /**
     * Headers
     */
    private static final List<Header> defaultHeaders;

    /**
     * RequestConfig
     */
    private static final RequestConfig defaultRequestConfig;

    /**
     * httpclient为单例,配置仅加载一次
     */
    static {
        /*
         * 加载配置文件
         */
        Properties p = getProperties("httputil.properties");
        props = initProps(p);

        /*
         * 初始化http连接池,支持https,也可以使用默认的无参构造
         */
        ConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register(
                "http", plainSocketFactory)
                .register("https", sslSocketFactory).build();
        manager = new PoolingHttpClientConnectionManager(registry);

        /*
         * socket配置,一般不修改HTTP connection相关配置,故不设置
         */
        SocketConfig socketConfig = SocketConfig.custom()
                //是否立即发送数据,设置为true会关闭Socket缓冲,默认为false
                .setTcpNoDelay((boolean) props.get("tcpNoDelay"))
                //是否可以在一个进程关闭Socket后,即使它还没有释放端口,其它进程还可以立即重用端口
                .setSoReuseAddress((boolean) props.get("soReuseAddress"))
                //接收数据的等待超时时间,单位ms
                .setSoTimeout((int) props.get("soTimeout"))
                //关闭Socket时,要么发送完所有数据,要么等待Xs后,就关闭连接,此时socket.close()是阻塞的
                .setSoLinger((int) props.get("soLinger"))
                //开启监视TCP连接是否有效
                .setSoKeepAlive((boolean) props.get("soKeepAlive"))
                .build();

        /*
         * header请求头相关配置
         */
        defaultHeaders = new ArrayList<>();
        String OSName = System.getProperty("os.name");
        defaultHeaders.add(new BasicHeader("Accept", "*/*"));
        defaultHeaders.add(new BasicHeader("User-Agent", "Mozilla/5.0 (" + OSName + "; VFramework/1.0.0; HttpClient/4.5)"));
        defaultHeaders.add(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.8"));
        defaultHeaders.add(new BasicHeader("Cache-Control", "max-age=0"));
        defaultHeaders.add(new BasicHeader("Connection", "keep-alive"));
        defaultHeaders.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));

        /*
         * request请求相关配置
         */
        defaultRequestConfig = RequestConfig.custom()
                //连接超时时间
                .setConnectTimeout((int) props.get("connectTimeout"))
                //读超时时间(等待数据超时时间)
                .setSocketTimeout((int) props.get("socketTimeout"))
                //从池中获取连接超时时间
                .setConnectionRequestTimeout((int) props.get("connectionRequestTimeout"))
                .build();

        /*
         * http连接池配置
         */
        manager.setMaxTotal((int) props.get("maxTotalPoolSize"));
        manager.setDefaultMaxPerRoute((int) props.get("defaultMaxPerRoute"));
        manager.setDefaultSocketConfig(socketConfig);

        /*
         * 获取连接对象
         */
        client = HttpClients.custom()
                .disableAuthCaching()
                .setConnectionManager(manager)
                .setDefaultRequestConfig(defaultRequestConfig)
                .setDefaultHeaders(defaultHeaders)
                //不开启重试
                .setRetryHandler(new DefaultHttpRequestRetryHandler((int) props.get("retryCount"), false))
                .build();
    }

    /**
     * 默认UTF-8编码
     *
     * @param url      地址
     * @param paramMap 参数kv
     * @return String
     */
    public static String doGet(String url, Map<String, String> paramMap) throws BusinessException {
        return doGet(url, paramMap, StandardCharsets.UTF_8);
    }

    /**
     * Get请求
     *
     * @param url      地址
     * @param paramMap 参数kv
     * @param encode   编码
     * @return String
     * @throws BusinessException 交给应用层处理异常
     */
    public static String doGet(String url, Map<String, String> paramMap, Charset encode) throws BusinessException {
        String result = null;
        // 设置请求参数
        URI uri = getUriWithParams(url, paramMap);
        HttpGet httpGet = new HttpGet(uri);
        // 设置Request配置
        httpGet.setConfig(defaultRequestConfig);
        // 响应
        CloseableHttpResponse response = null;
        try {
            result = getResponseContent(httpGet, encode);
        } catch (IOException e) {
            log.error("HTTP GET: failed to get response content! e:{}", e, e.getMessage());
            throw new BusinessException(ResultCodeEnum.HTTPCLIENT_REQUEST_FAILED, e);
        }
        return result;
    }

    /**
     * 默认UTF-8编码
     *
     * @param url      地址
     * @param paramMap KV参数(form-data)
     * @return String
     */
    public static String doPost(String url, Map<String, String> paramMap) throws BusinessException {
        return doPost(url, paramMap, StandardCharsets.UTF_8);
    }

    /**
     * post请求
     *
     * @param url      地址
     * @param paramMap KV参数(form-data)
     * @param encode   编码
     * @return String
     * @throws BusinessException 交给应用层处理异常
     */
    public static String doPost(String url, Map<String, String> paramMap, Charset encode) throws BusinessException {
        String result = null;
        // 设置请求参数
        URI uri = getUriWithParams(url, paramMap);
        HttpPost httpPost = new HttpPost(uri);
        // 设置Request配置
        httpPost.setConfig(defaultRequestConfig);
        //设置post请求头
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + encode);
        try {
            result = getResponseContent(httpPost, encode);
        } catch (IOException e) {
            log.error("HTTP POST: failed to get response content! e:{}", e, e.getMessage());
            throw new BusinessException(ResultCodeEnum.HTTPCLIENT_REQUEST_FAILED, e);
        }
        return result;
    }

    /**
     * 默认UTF-8编码
     *
     * @param url        地址
     * @param jsonObject json参数
     * @return String
     */
    public static String doPost(String url, Object jsonObject) throws BusinessException {
        return doPost(url, jsonObject, StandardCharsets.UTF_8);
    }

    /**
     * @param url        地址
     * @param jsonObject json参数
     * @param encode     编码
     * @return String
     */
    public static String doPost(String url, Object jsonObject, Charset encode) throws BusinessException {
        // 将Object转换为json字符串
        String jsonString = JSON.toJSONString(jsonObject);
        return doPost(url, jsonString, encode);
    }

    /**
     * 默认UTF-8编码
     *
     * @param url        地址
     * @param jsonString json字符串参数
     * @return String
     */
    public static String doPost(String url, String jsonString) throws BusinessException {
        return doPost(url, jsonString, StandardCharsets.UTF_8);
    }

    /***
     * @param url  地址
     * @param jsonString json字符串参数
     * @param encode 编码
     * @return String
     * @throws BusinessException 交给应用层处理异常
     */
    public static String doPost(String url, String jsonString, Charset encode) throws BusinessException {
        String result = null;
        //设置json参数
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(jsonString, encode);
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=" + encode);
        try {
            result = getResponseContent(httpPost, encode);
        } catch (IOException e) {
            log.error("HTTP POST: failed to get response content! e:{}", e, e.getMessage());
            throw new BusinessException(ResultCodeEnum.HTTPCLIENT_REQUEST_FAILED);
        }
        return result;
    }

    /**
     * 关闭连接池,可以显示地外部调用关闭
     */
    public static void closeConnectionPool() {
        try {
            client.close();
            manager.close();
        } catch (IOException e) {
            log.error("failed to close httpclient! e:{}", e, e.getMessage());
        }
    }

    /**
     * 从response获取contentStr,内部释放request资源
     *
     * @param request http请求
     * @param encode  编码
     * @return String
     * @throws BusinessException 该异常由execute或解析response抛出
     */
    private static String getResponseContent(HttpRequestBase request, Charset encode) throws IOException {
        String result = null;
        CloseableHttpResponse response = null;
        try {
            response = client.execute(request);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            //状态示例:HTTP/1.1 200 OK
            log.info("响应状态:{}", response.getStatusLine());
            if (responseEntity != null) {
                //设置解码
                result = EntityUtils.toString(responseEntity, encode);
                log.info("响应内容:{}", result);
            }
        } finally {
            request.releaseConnection();
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.info("failed to close response! e: {}", e, e.getMessage());
                }
            }
        }
        return result;
    }

    /**
     * 将参数KV添加到uri
     *
     * @param url      地址
     * @param paramMap KV参数
     * @return URI
     */
    private static URI getUriWithParams(String url, Map<String, String> paramMap) {
        URI uri;
        try {
            // 将参数放入键值对类NameValuePair数组中,作为uri参数
            NameValuePair[] params = getNameValuePair(paramMap);
            if (params != null) {
                uri = new URIBuilder(url).setParameters(params).build();
            } else {
                uri = new URIBuilder(url).build();
            }
        } catch (URISyntaxException e1) {
            log.error("failed to set request parameter!");
            throw new RuntimeException("设置请求参数失败!");
        }
        return uri;
    }

    /**
     * 根据paramMap生成NameValuePair数组,放入RequestBody
     *
     * @param paramMap KV参数
     * @return NameValuePair
     */
    private static NameValuePair[] getNameValuePair(Map<String, String> paramMap) {
        if (MapUtils.isEmpty(paramMap)) {
            return null;
        }
        NameValuePair[] params = new NameValuePair[paramMap.size()];
        Iterator<Map.Entry<String, String>> it = paramMap.entrySet().iterator();
        int i = 0;
        while (it.hasNext()) {
            Map.Entry<String, String> map = it
                    .next();
            params[i] = new BasicNameValuePair(map.getKey(), map.getValue());
            i++;
        }
        return params;
    }

    /**
     * 加载排位置文件中的httpclient参数
     *
     * @param filename properties文件路径
     * @return Properties
     */
    private static Properties getProperties(String filename) {
        Properties p = new Properties();
        InputStream propertiesAsStream = HttpClientUtil.class.getClassLoader().getResourceAsStream(filename);
        try {
            p.load(propertiesAsStream);
        } catch (IOException e) {
            log.error("failed to load properties {}", e);
        } finally {
            Optional.ofNullable(propertiesAsStream).ifPresent(prop -> {
                try {
                    prop.close();
                } catch (IOException e) {
                    log.error("failed to get or close InputStream {}", e);
                }
            });
        }
        return p;
    }

    /**
     * 加载properties配置到缓存
     *
     * @param properties Properties
     * @return Map
     */
    private static Map<String, Object> initProps(Properties properties) {
        Map<String, Object> cache = Maps.newHashMap();
        Integer retryCount = Integer.parseInt(properties.getProperty("retryCount"));
        Integer maxTotalPoolSize = Integer.parseInt(properties.getProperty("http.total.max.poolsize"));
        Integer defaultMaxPerRoute = Integer.parseInt(properties.getProperty("http.default.max.per.route"));
        Boolean tcpNoDelay = Boolean.parseBoolean(properties.getProperty("http.tcp.no.delay"));
        Boolean soReuseAddress = Boolean.parseBoolean(properties.getProperty("http.tcp.reuse.address"));
        Integer soTimeout = Integer.parseInt(properties.getProperty("http.so.timeout"));
        Integer soLinger = Integer.parseInt(properties.getProperty("http.so.linger"));
        Boolean soKeepAlive = Boolean.parseBoolean(properties.getProperty("http.so.keepalive"));
        Integer connectTimeout = Integer.parseInt(properties.getProperty("http.connection.timeout"));
        Integer socketTimeout = Integer.parseInt(properties.getProperty("http.socket.timeout"));
        Integer connectionRequestTimeout = Integer.parseInt(properties.getProperty("http.connection.request.timeout"));
        cache.put("retryCount", retryCount);
        cache.put("maxTotalPoolSize", maxTotalPoolSize);
        cache.put("defaultMaxPerRoute", defaultMaxPerRoute);
        cache.put("tcpNoDelay", tcpNoDelay);
        cache.put("soReuseAddress", soReuseAddress);
        cache.put("soTimeout", soTimeout);
        cache.put("soLinger", soLinger);
        cache.put("soKeepAlive", soKeepAlive);
        cache.put("connectTimeout", connectTimeout);
        cache.put("socketTimeout", socketTimeout);
        cache.put("connectionRequestTimeout", connectionRequestTimeout);
        return cache;
    }
}

httputil.property

# \u5B57\u7B26\u96C6
http.content.encoding=UTF-8

# \u91CD\u8BD5\u6B21\u6570
retryCount = 3
# \u6700\u5927\u8FDE\u63A5\u6C60\u8FDE\u63A5\u6570
http.total.max.poolsize=1000
# \u9ED8\u8BA4\u7684\u6BCF\u4E2A\u8DEF\u7531\u7684\u6700\u5927\u8FDE\u63A5\u6570
http.default.max.per.route=400
# Socket tcp no delay
http.tcp.no.delay=true
# Socket reuse port
http.tcp.reuse.address=true
# socket \u8BFB\u5199\u8D85\u65F6\u65F6\u95F4
http.so.timeout=3000
# \u5173\u95EDSocket\u65F6\uFF0C\u8981\u4E48\u53D1\u9001\u5B8C\u6240\u6709\u6570\u636E\uFF0C\u8981\u4E48\u7B49\u5F855s\u540E\uFF0C\u5C31\u5173\u95ED\u8FDE\u63A5\uFF0C\u6B64\u65F6socket.close()\u662F\u963B\u585E\u7684
http.so.linger=5
# Socket keep alive
http.so.keepalive=true
# \u8FDE\u63A5\u8D85\u65F6
http.connection.timeout=3000
# \u8BFB\u8D85\u65F6\uFF08\u7B49\u5F85\u6570\u636E\u8D85\u65F6\u65F6\u95F4\uFF09
http.socket.timeout=3000
# \u4ECE\u6C60\u4E2D\u83B7\u53D6\u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4
http.connection.request.timeout=500

(2)第二种(推荐,这种是在做支付下单时写的,经过线上支付的检验)

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.entity.ByteArrayEntity;
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.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author AA
 * @description httpClient工具, 仅实现了GET和POST
 * @date 2020/8/13
 */
public class HttpClientUtil {

    public static final String HTTP_METHOD_GET = "GET";

    public static final String HTTP_METHOD_POST = "POST";

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);

    private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8");

    private static final ObjectMapper objectMapper;

    private static final CloseableHttpClient httpClient;

    private static final int DEFAULT_POOL_MAX_TOTAL = 400;

    private static final int DEFAULT_POOL_PER_ROUTE = 400;

    private static final int DEFAULT_TIMEOUT = 3000;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        List<Header> defaultHeaders = new ArrayList<>();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

        int poolMaxTotal = getMaxTotalConfig();
        int poolMaxPerRoute = getMaxPerRouteConfig();
        LOGGER.info("Common HttpClient MaxTotal:{}", poolMaxTotal);
        LOGGER.info("Common HttpClient DefaultMaxPerRoute:{}", poolMaxPerRoute);
        connManager.setMaxTotal(poolMaxTotal);
        connManager.setDefaultMaxPerRoute(poolMaxPerRoute);

        String osname = System.getProperty("os.name");
        defaultHeaders.add(new BasicHeader("Accept", "*/*"));
        defaultHeaders.add(new BasicHeader("User-Agent", "Mozilla/5.0 (" + osname + "; VFramework/1.0.0; HttpClient/4.5)"));
        defaultHeaders.add(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.8"));
        defaultHeaders.add(new BasicHeader("Cache-Control", "max-age=0"));
        defaultHeaders.add(new BasicHeader("Connection", "keep-alive"));
        defaultHeaders.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.disableCookieManagement();
        builder.setDefaultHeaders(defaultHeaders);
        builder.setConnectionManager(connManager);
        httpClient = builder.build();
        LOGGER.info("Common_HttpClient_initialized!");
    }

    public static HttpClient getHttpClient() {
        return httpClient;
    }

    /**
     * 默认的每个路由的最大连接数,可读配置中心
     */
    private static int getMaxPerRouteConfig() {
        try {
            return ConfigManager.getInteger("common.httpClient.pool.maxPerRoute", DEFAULT_POOL_PER_ROUTE);
        } catch (Exception e) {
            LOGGER.warn("获取配置common.httpClient.pool.maxPerRoute时出错, {}", e.getMessage());
        }
        return DEFAULT_POOL_PER_ROUTE;
    }

    /**
     * 最大连接池连接数,可读配置中心
     */
    private static int getMaxTotalConfig() {
        try {
            return ConfigManager.getInteger("common.httpClient.pool.maxTotal", DEFAULT_POOL_MAX_TOTAL);
        } catch (Exception e) {
            LOGGER.warn("获取配置common.httpClient.pool.maxTotal时出错, {}", e.getMessage());
        }
        return DEFAULT_POOL_MAX_TOTAL;
    }

    public static <T> T sendData(String url, String httpMethod, HttpContentTypeEnum contentType, Object parameter, Map<String, String> headers, int timeout,
                                 TypeReference<T> typeReference) {
        return sendData(url, httpMethod, contentType, parameter, headers, timeout, typeReference, true);
    }

    public static <T> T sendGet(String url, Object parameter, Map<String, String> headers, TypeReference<T> typeReference) {
        return sendData(url, HTTP_METHOD_GET, null, parameter, headers, DEFAULT_TIMEOUT, typeReference, true);
    }

    public static String sendGet(String url, Object parameter, Map<String, String> headers) {
        return sendData(url, HTTP_METHOD_GET, null, parameter, headers, DEFAULT_TIMEOUT, new TypeReference<String>() {
        }, true);
    }

    public static String sendGet(String url, Object parameter) {
        return sendData(url, HTTP_METHOD_GET, null, parameter, null, DEFAULT_TIMEOUT, new TypeReference<String>() {
        }, true);
    }

    public static <T> T sendGet(String url, Object parameter, Map<String, String> headers, int timeout, TypeReference<T> typeReference) {
        return sendData(url, HTTP_METHOD_GET, null, parameter, headers, timeout, typeReference, true);
    }

    /**
     * 按urlencoding方式提交
     */
    public static <T> T sendPostForm(String url, Object parameter, Map<String, String> headers, TypeReference<T> typeReference) {
        return sendData(url, HTTP_METHOD_POST, HttpContentTypeEnum.URL_ENCODING, parameter, headers, DEFAULT_TIMEOUT, typeReference, true);
    }

    public static String sendPostForm(String url, Object parameter, Map<String, String> headers) {
        return sendData(url, HTTP_METHOD_POST, HttpContentTypeEnum.URL_ENCODING, parameter, headers, DEFAULT_TIMEOUT, new TypeReference<String>() {
        }, true);
    }

    public static String sendPostForm(String url, Object parameter) {
        return sendData(url, HTTP_METHOD_POST, HttpContentTypeEnum.URL_ENCODING, parameter, null, DEFAULT_TIMEOUT, new TypeReference<String>() {
        }, true);
    }

    public static <T> T sendPostForm(String url, Object parameter, Map<String, String> headers, int timeout, TypeReference<T> typeReference) {
        return sendData(url, HTTP_METHOD_POST, HttpContentTypeEnum.URL_ENCODING, parameter, headers, timeout, typeReference, true);
    }

    /**
     * 按json方式提交
     */
    public static <T> T sendPostJson(String url, Object parameter, Map<String, String> headers, TypeReference<T> typeReference) {
        return sendData(url, HTTP_METHOD_POST, HttpContentTypeEnum.JSON, parameter, headers, DEFAULT_TIMEOUT, typeReference, true);
    }

    public static String sendPostJson(String url, Object parameter, Map<String, String> headers) {
        return sendData(url, HTTP_METHOD_POST, HttpContentTypeEnum.JSON, parameter, headers, DEFAULT_TIMEOUT, new TypeReference<String>() {
        }, true);
    }

    public static String sendPostJson(String url, Object parameter) {
        return sendData(url, HTTP_METHOD_POST, HttpContentTypeEnum.JSON, parameter, null, DEFAULT_TIMEOUT, new TypeReference<String>() {
        }, true);
    }

    public static <T> T sendPostJson(String url, Object parameter, Map<String, String> headers, int timeout, TypeReference<T> typeReference) {
        return sendData(url, HTTP_METHOD_POST, HttpContentTypeEnum.JSON, parameter, headers, timeout, typeReference, true);
    }

    @SuppressWarnings("unchecked")
    public static <T> T sendData(String url, String httpMethod, HttpContentTypeEnum contentType, Object parameter, Map<String, String> headers, int timeout,
                                 TypeReference<T> typeReference, boolean encodeQuery) {
        boolean success = false;
        long st = System.currentTimeMillis();
        String host = null;

        CloseableHttpResponse response = null;
        try {

            StringBuilder uri = new StringBuilder();
            uri.append(url);
            HttpRequestBase request;
            if (httpMethod.equals(HTTP_METHOD_GET)) {
                if (parameter != null) {
                    // Http Parameters
                    Object o = parameter;
                    Map<?, ?> m = convertToMap(o);
                    boolean first = true;
                    for (Map.Entry<?, ?> e : m.entrySet()) {
                        Object k = e.getKey();
                        Object v = e.getValue();
                        if (k != null && v != null) {
                            if (first) {
                                uri.append("?");
                            } else {
                                uri.append("&");
                            }
                            uri.append(k.toString()).append("=").append(v.toString());
                            first = false;
                        }
                    }

                }
                if (encodeQuery) {
                    request = new HttpGet(UriUtils.encodeQuery(uri.toString(), "UTF-8"));
                } else {
                    request = new HttpGet(uri.toString());
                }
                if (headers != null) {
                    // Http Headers
                    setHeaders(request, headers);
                }
            } else if (httpMethod.equals(HTTP_METHOD_POST)) {
                HttpPost post;
                if (encodeQuery) {
                    post = new HttpPost(UriUtils.encodeQuery(uri.toString(), "UTF-8"));
                } else {
                    post = new HttpPost(uri.toString());
                }

                request = post;
                if (headers != null) {
                    // Http Headers
                    setHeaders(request, headers);
                }
                if (contentType == HttpContentTypeEnum.URL_ENCODING) {
                    if (parameter != null) {
                        // Http Parameters
                        List<NameValuePair> parameters = new ArrayList<>();
                        Object o = parameter;
                        Map<?, ?> m = convertToMap(o);
                        for (Map.Entry<?, ?> e : m.entrySet()) {
                            Object k = e.getKey();
                            Object v = e.getValue();
                            if (k != null && v != null) {
                                parameters.add(new BasicNameValuePair(k.toString(), v.toString()));
                            }
                        }
                        post.setEntity(new UrlEncodedFormEntity(parameters, CHARSET_UTF8));
                    }

                } else {
                    byte[] bytes = null;
                    if (contentType == HttpContentTypeEnum.JSON) {
                        if (parameter instanceof String) {
                            bytes = ((String) parameter).getBytes(CHARSET_UTF8);
                        } else if (parameter != null) {
                            bytes = objectMapper.writeValueAsBytes(parameter);
                            //LOGGER.debug("data:{}",new String(bytes));
                        }
                        request.setHeader(HttpHeaders.CONTENT_TYPE, contentType.getContentType());
                        if (headers != null) {
                            // Http Headers
                            setHeaders(request, headers);
                        }
                    } else {
                        if (parameter instanceof String) {
                            bytes = ((String) parameter).getBytes(CHARSET_UTF8);
                        } else {
                            bytes = objectMapper.writeValueAsBytes(parameter);
                        }
                    }
                    if (bytes != null) {
                        ByteArrayEntity entity = new ByteArrayEntity(bytes);
                        post.setEntity(entity);
                    }
                }

            } else {
                throw new IllegalArgumentException("Http method not supported: " + httpMethod);
            }

            // 设置请求超时时间
            RequestConfig.Builder builder = RequestConfig.custom();
            builder.setSocketTimeout(timeout).setConnectTimeout(timeout).setConnectionRequestTimeout(timeout);

            RequestConfig config = builder.build();
            request.setConfig(config);
            host = request.getURI().getHost();

            LOGGER.debug("Start to invoke url:{}", uri.toString());
            response = httpClient.execute(request);
            int status = response.getStatusLine().getStatusCode();
            if (status == 200 || status == 201) {
                success = true;
                boolean readEntity = true;
                Header header = response.getFirstHeader("Content-Length");
                if (header != null) {
                    long contentLength = NumberUtils.toLong(header.getValue(), 0);
                    if (contentLength == 0) {
                        readEntity = false;
                    }
                }
                HttpEntity entity = response.getEntity();
                if (entity != null && readEntity) {
                    T result = null;
                    InputStream content = entity.getContent();
                    try {
                        if (typeReference.getType() == String.class) {
                            String resultString = IOUtils.toString(content);
                            LOGGER.debug("response: {}", resultString);
                            result = (T) resultString;
                        } else {
                            result = objectMapper.readValue(content, typeReference);
                        }
                    } finally {
                        IOUtils.closeQuietly(content);
                    }
                    return result;
                } else {
                    return null;
                }
            } else if (status == 204) {
                return null;
            } else {
                throw new RuntimeException("Invoke Remote Server:" + url + " Failed, Status Code:" + status);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            long et = System.currentTimeMillis();
            long time = et - st;
            LOGGER.debug("host:{}, method:{}, success:{}, time:{}", host, httpMethod, success, time);
            IOUtils.closeQuietly(response);
        }
    }

    private static void setHeaders(HttpRequestBase request, Map<String, String> headers) {
        if (headers != null) {
            for (Map.Entry<?, ?> e : headers.entrySet()) {
                Object k = e.getKey();
                Object v = e.getValue();
                if (k != null && v != null) {
                    request.setHeader(k.toString(), v.toString());
                }
            }
        }
    }

    /**
     * 将参数对象转换成Map
     */
    private static Map<?, ?> convertToMap(Object o) throws Exception {
        if (o instanceof Map) {
            return (Map<?, ?>) o;
        }
        if (o instanceof List) {
            throw new IllegalArgumentException("Object cannot instanceof list,Class:" + o.getClass().getName());
        }
        Map<String, String> map = new HashMap<String, String>();
        BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass());
        PropertyDescriptor[] proDescrtptors = beanInfo.getPropertyDescriptors();
        if (proDescrtptors != null && proDescrtptors.length > 0) {
            for (PropertyDescriptor propDesc : proDescrtptors) {
                Method readMethod = propDesc.getReadMethod();
                Method writeMethod = propDesc.getWriteMethod();
                if (readMethod != null && writeMethod != null) {
                    String propertyName = propDesc.getName();
                    Object p = readMethod.invoke(o);
                    if (p != null) {
                        map.put(propertyName, p.toString());
                    }
                }
            }
        }
        return map;
    }

}
import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * @author AA
 * @description httpClient post请求类型枚举
 * @date 2020/8/13
 */
@AllArgsConstructor
@Getter
public enum HttpContentTypeEnum {

    /**
     * json请求
     */
    JSON("application/json; charset=UTF-8"),

    /**
     * urlencoded请求
     */
    URL_ENCODING("application/x-www-form-urlencoded; charset=UTF-8");

    private final String contentType;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值