Org. apache. httpcomponents: httpclient tool class, java tool class

Source: Internet
Author: User

Org. apache. httpcomponents: httpclient tool class, java tool class

Httpclient version 4.4.1

Because http connections require three handshakes, resources and time are wasted when frequent calls are required.

Therefore, the connection pool is used for connection.

Change the maximum connection pool connections and maximum route connections as needed

Another thing to note is that

 

// Release the Socket stream response. close (); // release 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. httpReq UestBase; 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/*** Created by lazada on. 26 */27 public class HttpClientUtils {28 private static PoolingHttpClientConnectionManager cm; 29 private static String EMPTY_STR = ""; 30 pr Ivate 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); // The maximum number of connections in the entire connection pool is 40 cm. setdefamaxmaxperroute (5); // maximum number of connections per route. The default value is 2 41 SocketConfig SC = SocketConfig. custom (). setSoTimeout (SO_TIMEOUT_MS ). build (); 42 cm. setdefasocksocketconfig (SC); 43} 44} 45 46/** 47 * Get HttpClient 48*49 * @ return 50 */51 private static CloseableHttpClient getHttpClient () through the connection pool () {52 init (); 53 return HttpClients. custom (). setConnectionManager (cm ). setConnectionManagerShared (tr Ue ). 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. setParameter S (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 (httpPos T); 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); // to send json data, you must set contentType118 httpPost. setEntity (s); 119 return getResult (httpPost); 120} 121 122 123 private static Ar RayList <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 * handle Http request 134*135 * @ param request136 * @ return#*/138 private static Strin G 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 Close AbleHttpResponse response = null; 149 try {150 response = httpClient.exe cute (request); 151 // response. getStatusLine (). getStatusCode (); 152 HttpEntity entity = response. getEntity (); 153 if (entity! = Null) {154 // long len = entity. getContentLength (); //-1 indicates that the length is unknown. 155 return EntityUtils. toString (entity); 156} 157} catch (IOException e) {158 e. printStackTrace (); 159} finally {160 try {161 // release the Socket stream 162 response. close (); 163 // release Connection164 // httpClient. close (); 165} catch (IOException e) {166 e. printStackTrace (); 167} 168} 169 170 return EMPTY_STR; 171} 172 173}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.