Java HttpClientUtil 工具类

package com.jasonote.tools.util;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description: [HTTP CLIENT]
 * @Author: Jasonote
 * @CreateDate: 17/11/08 15:14
 * @Version: [v1.0]
 */
public class HttpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static final int DEFAULT_SOCKET_TIMEOUT = 15000;
    public static final int DEFAULT_CONNECT_TIMEOUT = 15000;
    public static final int DEFAULT_CONNECTION_REQUEST_TIMEOUT = 15000;


    /**
     * http请求相关操作
     *
     * @param url        url
     * @param jsonEntity jsonEntity
     * @return return
     */
    public static String postJson(String url, String jsonEntity) {
        RequestConfig config = RequestConfig.custom()
                .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
                .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
                .build();

        HashMap<String, String> appendHeaders = new HashMap<>();
        return postJson(url, jsonEntity, appendHeaders, config);
    }


    public static <T> T postJsonWithConfig(String url, String jsonEntity, RequestConfig requestConfig, HttpClientUtilCallback<T> callback) {
        if (requestConfig == null) {
            requestConfig = RequestConfig.custom()
                    .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                    .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
                    .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
                    .build();
        }


        HashMap<String, String> appendHeaders = new HashMap<>();
        String jsonString = postJson(url, jsonEntity, appendHeaders, requestConfig);

        T result = null;
        try {
            result = callback.callback(jsonString);
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }


    public static <T> T postJson(String url, String jsonEntity, HttpClientUtilCallback<T> callback) {
        RequestConfig config = RequestConfig.custom()
                .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
                .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
                .build();

        HashMap<String, String> appendHeaders = new HashMap<>();
        String jsonString = postJson(url, jsonEntity, appendHeaders, config);

        T result = null;
        try {
            result = callback.callback(jsonString);
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }

    public static <T> T postJson(String url, Map requestBody, HttpClientUtilCallback<T> callback) {
        T result = null;
        try {
            RequestConfig config = RequestConfig.custom()
                    .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                    .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
                    .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
                    .build();

            HashMap<String, String> appendHeaders = new HashMap<>();
            String jsonParam = "";
            jsonParam = JsonUtilNew.writeValueAsString(requestBody);
            String jsonString = postJson(url, jsonParam, appendHeaders, config);
            result = callback.callback(jsonString);
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }


    /**
     * http请求相关操作
     *
     * @param url            url
     * @param jsonEntity     jsonEntity
     * @param appendHearders appendHeaders
     * @param config         config
     * @return return
     */
    public static String postJson(String url, String jsonEntity, Map<String, String> appendHearders, RequestConfig config) {
        CloseableHttpClient httpClient = TraceHttpClientBuilder.create().setDefaultRequestConfig(config).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(config);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.addHeader("Connection", "Keep-Alive");
        httpPost.addHeader("user-agent", "JASONOTE/Wang");

        if (appendHearders != null && !appendHearders.isEmpty()) {
            Iterator<Map.Entry<String, String>> iterator = appendHearders.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        //设置请求消息体
        if (!StringUtils.isEmpty(jsonEntity)) {
            httpPost.setEntity(new StringEntity(jsonEntity, Consts.UTF_8.name()));
        }

        String result = "";
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        LogUtil.printPostInfo(logger, url, jsonEntity, result);
        return result;
    }
}

Jason.wang

When you find your talent can't afford to be ambitious, be quiet and study !

You may also like...