org.apache.httpcomponents:httpclient 工具類,java工具類

來源:互聯網
上載者:User

org.apache.httpcomponents:httpclient 工具類,java工具類

基於httpclient 版本4.4.1

因為http串連需要三向交握,在需要頻繁調用時浪費資源和時間

故採用串連池的方式串連

  根據實際需要更改  串連池最大串連數、路由最大串連數

  另一個需要注意的是

 

   // 釋放Socket流     response.close();     // 釋放Connection     // httpClient.close();

  1 import org.apache.http.HttpEntity;  2 import org.apache.http.NameValuePair;  3 import org.apache.http.client.config.RequestConfig;  4 import org.apache.http.client.entity.UrlEncodedFormEntity;  5 import org.apache.http.client.methods.CloseableHttpResponse;  6 import org.apache.http.client.methods.HttpGet;  7 import org.apache.http.client.methods.HttpPost;  8 import org.apache.http.client.methods.HttpRequestBase;  9 import org.apache.http.client.utils.URIBuilder; 10 import org.apache.http.config.SocketConfig; 11 import org.apache.http.entity.StringEntity; 12 import org.apache.http.impl.client.CloseableHttpClient; 13 import org.apache.http.impl.client.HttpClients; 14 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 15 import org.apache.http.message.BasicNameValuePair; 16 import org.apache.http.util.EntityUtils; 17  18 import java.io.IOException; 19 import java.io.UnsupportedEncodingException; 20 import java.net.URISyntaxException; 21 import java.util.ArrayList; 22 import java.util.Map; 23  24 /** 25  * Created by lidada on 2017/6/9. 26  */ 27 public class HttpClientUtils { 28     private static PoolingHttpClientConnectionManager cm; 29     private static String EMPTY_STR = ""; 30     private static String CONTENT_TYPE_UTF_8 = "UTF-8"; 31     private static String CONTENT_TYPE_GBK = "GBK"; 32     private static String CONTENT_TYPE_JSON = "application/json"; 33     private static final int CONNECTION_TIMEOUT_MS = 60000; 34     private static final int SO_TIMEOUT_MS = 60000; 35  36     private static void init() { 37         if (cm == null) { 38             cm = new PoolingHttpClientConnectionManager(); 39             cm.setMaxTotal(50);// 整個串連池最大串連數 40             cm.setDefaultMaxPerRoute(5);// 每路由最大串連數,預設值是2 41             SocketConfig sc = SocketConfig.custom().setSoTimeout(SO_TIMEOUT_MS).build(); 42             cm.setDefaultSocketConfig(sc); 43         } 44     } 45  46     /** 47      * 通過串連池擷取HttpClient 48      * 49      * @return 50      */ 51     private static CloseableHttpClient getHttpClient() { 52         init(); 53         return HttpClients.custom().setConnectionManager(cm).setConnectionManagerShared(true) .build(); 54     } 55  56     public static String httpGetRequest(String url) { 57         HttpGet httpGet = new HttpGet(url); 58         return getResult(httpGet); 59     } 60  61     public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException { 62         URIBuilder ub = new URIBuilder(); 63         ub.setPath(url); 64  65         ArrayList<NameValuePair> pairs = covertParams2NVPS(params); 66         ub.setParameters(pairs); 67  68         HttpGet httpGet = new HttpGet(ub.build()); 69         return getResult(httpGet); 70     } 71  72     public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params) 73             throws URISyntaxException { 74         URIBuilder ub = new URIBuilder(); 75         ub.setPath(url); 76  77         ArrayList<NameValuePair> pairs = covertParams2NVPS(params); 78         ub.setParameters(pairs); 79  80         HttpGet httpGet = new HttpGet(ub.build()); 81         for (Map.Entry<String, Object> param : headers.entrySet()) { 82             httpGet.addHeader(param.getKey(), String.valueOf(param.getValue())); 83         } 84         return getResult(httpGet); 85     } 86  87     public static String httpPostRequest(String url) { 88         HttpPost httpPost = new HttpPost(url); 89         return getResult(httpPost); 90     } 91  92     public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException { 93         HttpPost httpPost = new HttpPost(url); 94         ArrayList<NameValuePair> pairs = covertParams2NVPS(params); 95         httpPost.setEntity(new UrlEncodedFormEntity(pairs, CONTENT_TYPE_UTF_8)); 96         return getResult(httpPost); 97     } 98  99     public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)100             throws UnsupportedEncodingException {101         HttpPost httpPost = new HttpPost(url);102 103         for (Map.Entry<String, Object> param : headers.entrySet()) {104             httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));105         }106 107         ArrayList<NameValuePair> pairs = covertParams2NVPS(params);108         httpPost.setEntity(new UrlEncodedFormEntity(pairs, CONTENT_TYPE_UTF_8));109 110         return getResult(httpPost);111     }112 113     public static String httpPostJSON(String url, String json) throws UnsupportedEncodingException {114         HttpPost httpPost = new HttpPost(url);115         StringEntity s = new StringEntity(json);116         s.setContentEncoding(CONTENT_TYPE_UTF_8);117         s.setContentType(CONTENT_TYPE_JSON);// 發送json資料需要設定contentType118         httpPost.setEntity(s);119         return getResult(httpPost);120     }121 122 123     private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {124         ArrayList<NameValuePair> pairs = new ArrayList<>();125         for (Map.Entry<String, Object> param : params.entrySet()) {126             pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));127         }128 129         return pairs;130     }131 132     /**133      * 處理Http請求134      *135      * @param request136      * @return137      */138     private static String getResult(HttpRequestBase request) {139 140         RequestConfig.Builder config = RequestConfig.copy(RequestConfig.DEFAULT);141         config.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);142         config.setSocketTimeout(SO_TIMEOUT_MS);143 144         request.setConfig(config.build());145 146         // CloseableHttpClient httpClient = HttpClients.createDefault();147         CloseableHttpClient httpClient = getHttpClient();148         CloseableHttpResponse response = null;149         try {150             response = httpClient.execute(request);151             // response.getStatusLine().getStatusCode();152             HttpEntity entity = response.getEntity();153             if (entity != null) {154                 // long len = entity.getContentLength();// -1 表示長度未知155                 return EntityUtils.toString(entity);156             }157         } catch (IOException e) {158             e.printStackTrace();159         } finally {160             try {161                 // 釋放Socket流162                 response.close();163                 // 釋放Connection164                 // httpClient.close();165             } catch (IOException e) {166                 e.printStackTrace();167             }168         }169 170         return EMPTY_STR;171     }172 173 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.