分享一個用HttpClient 實現的post和get請求的工具類

能夠參考spring 對其的封裝實現,參考java

org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter

HttpClientHelper 主要請求工具類 spring

@Slf4j
public class HttpClientHelper {
    /**
     * 字符編碼
     */
    private static  final String CHARSET="UTF-8";
    /**
     * 池化管理
     */
    private static PoolingHttpClientConnectionManager poolConnManager = null;
    /**
     * 能夠利用緩存的 httpClient
     */
    private static CloseableHttpClient httpClient;
    /**
     * 請求器的配置
     */
    private static RequestConfig requestConfig;


    static {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    builder.build());
            // 配置同時支持 HTTP 和 HTPPS
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
                    "http", PlainConnectionSocketFactory.getSocketFactory()).register(
                    "https", sslsf).build();
            // 初始化鏈接管理器
            poolConnManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            // 將最大鏈接數增長到200,實際項目最好從配置文件中讀取這個值
            poolConnManager.setMaxTotal(200);
            // 設置最大路由
            poolConnManager.setDefaultMaxPerRoute(2);
            // 根據默認超時限制初始化requestConfig
            int socketTimeout = 10000;
            int connectTimeout = 10000;
            int connectionRequestTimeout = 10000;
            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
                    connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
                    connectTimeout).build();

            // 初始化httpClient
            httpClient = getConnection();
        } catch (NoSuchAlgorithmException e) {
            log.error("NoSuchAlgorithmException",e);
        } catch (KeyStoreException e) {
            log.error("KeyStoreException",e);
        } catch (KeyManagementException e) {
            log.error("KeyManagementException",e);
        }
    }

    public static CloseableHttpClient getConnection() {
        CloseableHttpClient httpClient = HttpClients.custom()
                // 設置鏈接池管理
                .setConnectionManager(poolConnManager)
                // 設置請求配置
                .setDefaultRequestConfig(requestConfig)
                // 設置重試次數
                .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
                .build();

        if (poolConnManager != null && poolConnManager.getTotalStats() != null) {
            log.debug("now client pool "
                    + poolConnManager.getTotalStats().toString());
        }
        return httpClient;
    }

    public static String postJson(String url, Object object) {
        Assert.hasText(url, "url must not be null or empty string");
        String result = null;
        CloseableHttpResponse httpResponse = null;
        // 設置協議http和https對應的處理socket連接工廠的對象
        long startTime = System.currentTimeMillis();
        try {
            HttpPost httpPost = new HttpPost(url);

            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            String reqParams = object.toString();

            if (!(object instanceof String)) {
                reqParams = JsonUtil.toJSONString(object);
            }
            // 解決中文亂碼問題
            StringEntity stringEntity = new StringEntity(reqParams, CHARSET);
            stringEntity.setContentEncoding(CHARSET);

            httpPost.setEntity(stringEntity);
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, CHARSET);
            EntityUtils.consume(httpEntity);
        } catch (Exception e) {
            log.error("happen error", e);
        } finally {
            IOUtils.close(httpResponse);
        }
        log.info("http url {} cost {} ms", url, System.currentTimeMillis() - startTime);
        return result;
    }

    public static String post(String url, Map<String, Object> parameterMap) {
        Assert.hasText(url, "");
        String result = null;
        CloseableHttpResponse httpResponse = null;
        // 設置協議http和https對應的處理socket連接工廠的對象
        try {
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> nameValuePairs =  setNameValuePair(parameterMap);
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, CHARSET));
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, CHARSET);
            EntityUtils.consume(httpEntity);
        } catch (Exception e) {
           log.error("請求失敗",e);
        } finally {
            IOUtils.close(httpResponse);
        }
        return result;
    }

    public static String get(String url) {
        return get(url,null);
    }

    public static String get(String url, Map<String, Object> parameterMap) {
        Assert.hasText(url, "");
        String result = null;
        CloseableHttpResponse httpResponse = null;
        // 設置協議http和https對應的處理socket連接工廠的對象
        try {
            List<NameValuePair> nameValuePairs = setNameValuePair(parameterMap);
            HttpGet httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?")
                    + EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, CHARSET)));
            httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, CHARSET);
            EntityUtils.consume(httpEntity);
        } catch (Exception e) {
            log.error("請求失敗",e);
        } finally {
            IOUtils.close(httpResponse);
        }
        return result;
    }

    /**
     * 將請求參數設置到 nameValuePairs 中
     * @param parameterMap
     * @return
     */
    private static List<NameValuePair> setNameValuePair( Map<String, Object> parameterMap){
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        if (parameterMap != null) {
            for (Entry<String, Object> entry : parameterMap.entrySet()) {
                String name = entry.getKey();
                String value = (String) entry.getValue();
                if (StringUtils.isNotEmpty(name)) {
                    nameValuePairs.add(new BasicNameValuePair(name, value));
                }
            }
        }
        return nameValuePairs;
    }

}

IOUtils 工具類json

import java.io.Closeable;
import java.io.IOException;

public class IOUtils {
    public static void close(Closeable closeable){
        if(closeable != null){
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
相關文章
相關標籤/搜索