HttpClientUtil
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClientUtil相关的知识,希望对你有一定的参考价值。
?????????contexts cep nec util gen soc pcl final manager
package com.hshbic.cloudapp.thirdserver.utils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.net.ssl.SSLContext; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; 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.config.Registry; import org.apache.http.config.RegistryBuilder; 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.ssl.SSLContexts; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author jff * */ public class HttpClientUtil { private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); /** ???????????? */ private final static int SOCKET_TIMEOUT = 60000; /** ???????????? */ private final static int CONNECTION_TIMEOUT = 10000; private final static int CONNECTION_REQUEST_TIMEOUT = 10000; /** ??????HOST????????????????????? */ private final static int MAX_CONN_PRE_HOST = 20; /** ??????????????????????????? */ private final static int MAX_CONN = 60; private final static String JSON_CHARSET = "application/json; charset=UTF-8"; /** * * @param url * @param headers * @param jsonData * @return * @throws Exception */ public static String doPost(String url,Map<String,String> headers,String jsonData)throws Exception { if(url==null){ throw new Exception("??????URL??????"); } CloseableHttpClient httpClient = getHttpClient(); HttpEntity responseEntity = null; HttpPost httppost = null; CloseableHttpResponse response = null; httppost = new HttpPost(url); try{ httppost.addHeader(HttpHeaders.CONTENT_TYPE, JSON_CHARSET); if (jsonData == null || jsonData.trim().length() <= 0) { throw new Exception("??????body??????"); } StringEntity stringEntity= new StringEntity(jsonData, "UTF-8"); httppost.setEntity(stringEntity); if (headers != null && headers.size() > 0) { for (Map.Entry<String, String> entry : headers.entrySet()) { httppost.addHeader(entry.getKey(), entry.getValue()); } } response = httpClient.execute(httppost); responseEntity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == statusCode) { return EntityUtils.toString(responseEntity); } else { throw new Exception("????????????????????? StatusCode=" + statusCode); } }catch(Exception e){ logger.error("POST?????? url= " + url + " ???????????????" + e); throw new Exception("POST???????????? url=" + url, e); }finally{ if (httppost != null) { httppost.releaseConnection(); } if (responseEntity != null) { try { responseEntity.getContent().close(); } catch (IOException e) { } } if (response != null) { try { response.close(); } catch (IOException e) { } } } } /** * * @param url * @param headers * @param requestParas ?????????????????? * @return * @throws Exception */ public static String doPost(String url,Map<String,String> headers,Map<String,String> requestParas)throws Exception { if(url==null){ throw new Exception("??????URL??????"); } CloseableHttpClient httpClient = getHttpClient(); HttpEntity responseEntity = null; HttpPost httppost = null; CloseableHttpResponse response = null; httppost = new HttpPost(url); try{ httppost.addHeader(HttpHeaders.CONTENT_TYPE, JSON_CHARSET); List<NameValuePair> form = new ArrayList<>(); if(requestParas!=null&&requestParas.size()>0){ for(String key: requestParas.keySet()){ if(key!=null&&key.length()>0){ form.add(new BasicNameValuePair(key, requestParas.get(key))); } } } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, Consts.UTF_8); httppost.setEntity(entity); if (headers != null && headers.size() > 0) { for (Map.Entry<String, String> entry : headers.entrySet()) { httppost.addHeader(entry.getKey(), entry.getValue()); } } response = httpClient.execute(httppost); responseEntity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == statusCode) { return EntityUtils.toString(responseEntity); } else { throw new Exception("????????????????????? StatusCode=" + statusCode); } }catch(Exception e){ logger.error("POST?????? url= " + url + " ???????????????" + e); throw new Exception("POST???????????? url=" + url, e); }finally{ if (httppost != null) { httppost.releaseConnection(); } if (responseEntity != null) { try { responseEntity.getContent().close(); } catch (IOException e) { } } if (response != null) { try { response.close(); } catch (IOException e) { } } } } /** * * @param url * @param headers * @return * @throws Exception */ public static String doGet(String url,Map<String,String> headers)throws Exception { if(url==null){ throw new Exception("??????URL??????"); } CloseableHttpClient httpClient = getHttpClient(); HttpEntity responseEntity = null; HttpGet httpGet = null; CloseableHttpResponse response = null; httpGet = new HttpGet(url); try{ httpGet.addHeader(HttpHeaders.CONTENT_TYPE, JSON_CHARSET); if (headers != null && headers.size() > 0) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpGet.addHeader(entry.getKey(), entry.getValue()); } } response = httpClient.execute(httpGet); responseEntity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == statusCode) { //logger.info(String.valueOf(statusCode)); return EntityUtils.toString(responseEntity); } else { throw new Exception("????????????????????? StatusCode=" + statusCode); } }catch(Exception e){ logger.error("?????? url= " + url + " ???????????????" + e); throw new Exception("???????????? url=" + url, e); }finally{ if (httpGet != null) { httpGet.releaseConnection(); } if (responseEntity != null) { try { responseEntity.getContent().close(); } catch (IOException e) { } } if (response != null) { try { response.close(); } catch (IOException e) { } } } } /** * ????????? CloseableHttpClient * @return CloseableHttpClient?????? */ public static CloseableHttpClient getHttpClient() { PoolingHttpClientConnectionManager connManager = null; RequestConfig requestConfig = null; try { SSLContext sslContext = SSLContexts.createSystemDefault(); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslContext)).build(); connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connManager.setMaxTotal(MAX_CONN); connManager.setDefaultMaxPerRoute(MAX_CONN_PRE_HOST); requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) .setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); } catch (Exception e) { logger.error("????????????PoolingHttpClientConnectionManager???RequestConfig????????????" + e); } return HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(requestConfig).build(); } }
以上是关于HttpClientUtil的主要内容,如果未能解决你的问题,请参考以下文章