Use of HttpClient and Notices

First, introduce some good websites: Introduction to httpclient: http://www.ibm.com/developerworks/cn/opensource/os-httpclient/ HTTP client certificat...

First, introduce some good websites:

Introduction to httpclient: http://www.ibm.com/developerworks/cn/opensource/os-httpclient/
HTTP client certificate import: http://www.blogjava.net/happytian/archive/2006/12/22/89447.html
Advanced knowledge of httpclient: http://laohuang.iteye.com/blog/55613
HTTP client official document: http://hc.apache.org/http components-client/index.html
HTTP client resource closure: http://www.iteye.com/topic/234759
Examples: http://blog.csdn.net/z69183787/article/details/19153369

And then, that's the sentence... Good things to reproduce, learn one can not be less, below Turn from here

I believe that the importance of the Http protocol does not need to say much. Compared with the URLConnection provided by traditional JDK, HttpClient adds ease of use and flexibility (specific differences, we will discuss later). It is not only easier for clients to send Http requests, but also for developers. test Interface (based on Http protocol) improves the efficiency of development and the robustness of code. Therefore, mastering HttpClient is a very important required content. After mastering HttpClient, I believe that the understanding of Http protocol will be more in-depth.

I. Introduction

HttpClient is a sub-project of Apache Jakarta Common. It provides an efficient, up-to-date and feature-rich client programming toolkit to support HTTP protocol, and it supports the latest version and recommendations of HTTP protocol. HttpClient has been used in many projects, such as Apache Jakarta and two other well-known open source projects, Cactus and HTMLUnit, which use HttpClient.

Download address: http://hc.apache.org/downloads.cgi

Two, characteristics

1. Standard-based, pure Java Language. Implementation of Http1.0 and Http1.1

2. All methods of Http (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) are implemented with extensible object-oriented structure.

3. Support HTTPS protocol.

4. Establish transparent connections through Http proxy.

5. Use CONNECT method to establish tunnel https connection through Http proxy.

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos authentication scheme.

7. Plug-in custom authentication scheme.

8. Portable and reliable socket factories make it easier to use third-party solutions.

9. Connection Manager supports multi-threaded applications. Supports setting the maximum number of connections, and also supports setting the maximum number of connections per host, discovering and closing outdated connections.

10. Automatically process Cookies in Set-Cookie.

11. Plug-in custom Cookie policy.

12. Request's output stream prevents content from being buffered directly to the socket server.

13. Response's input stream can effectively read the corresponding content directly from the socket server.

14. KeepAlive is used to maintain persistent connections in HTTP 1.0 and HTTP 1.1.

15. Get the response code and headers sent by the server directly.

16. Set the connection timeout capability.

17. Experimental support http1.1 response caching.

18. The source code is freely available based on Apache License.

III. Usage

Using HttpClient to send requests and receive responses is very simple. Generally, the following steps are needed.

1. Create the HttpClient object.

2. Create an instance of the request method and specify the request URL. If you need to send a GET request, create the HttpGet object; if you need to send a POST request, create the HttpPost object.

3. If you need to send request parameters, you can call HttpGet and HttpPost common setParams(HetpParams params) method to add request parameters; for HttpPost objects, you can also call setEntity(HttpEntity entity) method to set request parameters.

4. Call the execute(HttpUriRequest request) of the HttpClient object to send the request, which returns a HttpResponse.

5. The server's response header can be obtained by calling the getAllHeaders(), getHeaders(String name) of HttpResponse, and the HttpResponse's getEntity() method can be used to obtain the HttpEntity object, which wraps the server's response content. The program can get the response content of the server through this object.

6. Release the connection. Whether or not the execution method succeeds, the connection must be released

Four. Example
  1. public class HttpClientTest {
  2. @Test
  3. public void jUnitTest() {
  4. get();
  5. }
  6. /**
  7. * HttpClient Connect SSL
  8. */
  9. public void ssl() {
  10. CloseableHttpClient httpclient = null;
  11. try {
  12. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  13. FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
  14. try {
  15. //Load keyStore d:\tomcat.keystore
  16. trustStore.load(instream, "123456".toCharArray());
  17. } catch (CertificateException e) {
  18. e.printStackTrace();
  19. } finally {
  20. try {
  21. instream.close();
  22. } catch (Exception ignore) {
  23. }
  24. }
  25. //Believe in your CA and all self-signed certificates
  26. SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
  27. //Only TLSv1 protocol is allowed
  28. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
  29. SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
  30. httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
  31. //Create http requests (get mode)
  32. HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
  33. System.out.println("executing request" + httpget.getRequestLine());
  34. CloseableHttpResponse response = httpclient.execute(httpget);
  35. try {
  36. HttpEntity entity = response.getEntity();
  37. System.out.println("----------------------------------------");
  38. System.out.println(response.getStatusLine());
  39. if (entity != null) {
  40. System.out.println("Response content length: " + entity.getContentLength());
  41. System.out.println(EntityUtils.toString(entity));
  42. EntityUtils.consume(entity);
  43. }
  44. } finally {
  45. response.close();
  46. }
  47. } catch (ParseException e) {
  48. e.printStackTrace();
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. } catch (KeyManagementException e) {
  52. e.printStackTrace();
  53. } catch (NoSuchAlgorithmException e) {
  54. e.printStackTrace();
  55. } catch (KeyStoreException e) {
  56. e.printStackTrace();
  57. } finally {
  58. if (httpclient != null) {
  59. try {
  60. httpclient.close();
  61. } catch (IOException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. }
  66. }
  67. /**
  68. * post Form submission (simulated user login request)
  69. */
  70. public void postForm() {
  71. //Create a default httpClient instance.
  72. CloseableHttpClient httpclient = HttpClients.createDefault();
  73. //Create httppost
  74. HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
  75. //Create parameter queues
  76. List<namevaluepair> formparams = new ArrayList<namevaluepair>();
  77. formparams.add(new BasicNameValuePair("username", "admin"));
  78. formparams.add(new BasicNameValuePair("password", "123456"));
  79. UrlEncodedFormEntity uefEntity;
  80. try {
  81. uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
  82. httppost.setEntity(uefEntity);
  83. System.out.println("executing request " + httppost.getURI());
  84. CloseableHttpResponse response = httpclient.execute(httppost);
  85. try {
  86. HttpEntity entity = response.getEntity();
  87. if (entity != null) {
  88. System.out.println("--------------------------------------");
  89. System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
  90. System.out.println("--------------------------------------");
  91. }
  92. } finally {
  93. response.close();
  94. }
  95. } catch (ClientProtocolException e) {
  96. e.printStackTrace();
  97. } catch (UnsupportedEncodingException e1) {
  98. e1.printStackTrace();
  99. } catch (IOException e) {
  100. e.printStackTrace();
  101. } finally {
  102. //Close the connection and release resources
  103. try {
  104. httpclient.close();
  105. } catch (IOException e) {
  106. e.printStackTrace();
  107. }
  108. }
  109. }
  110. /**
  111. * Send a post request to access the local application and return different results depending on the passing parameters
  112. */
  113. public void post() {
  114. //Create a default httpClient instance.
  115. CloseableHttpClient httpclient = HttpClients.createDefault();
  116. //Create httppost
  117. HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
  118. //Create parameter queues
  119. List<namevaluepair> formparams = new ArrayList<namevaluepair>();
  120. formparams.add(new BasicNameValuePair("type", "house"));
  121. UrlEncodedFormEntity uefEntity;
  122. try {
  123. uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
  124. httppost.setEntity(uefEntity);
  125. System.out.println("executing request " + httppost.getURI());
  126. CloseableHttpResponse response = httpclient.execute(httppost);
  127. try {
  128. HttpEntity entity = response.getEntity();
  129. if (entity != null) {
  130. System.out.println("--------------------------------------");
  131. System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
  132. System.out.println("--------------------------------------");
  133. }
  134. } finally {
  135. response.close();
  136. }
  137. } catch (ClientProtocolException e) {
  138. e.printStackTrace();
  139. } catch (UnsupportedEncodingException e1) {
  140. e1.printStackTrace();
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. } finally {
  144. //Close the connection and release resources.
  145. try {
  146. httpclient.close();
  147. } catch (IOException e) {
  148. e.printStackTrace();
  149. }
  150. }
  151. }
  152. /**
  153. * Send get request
  154. */
  155. public void get() {
  156. CloseableHttpClient httpclient = HttpClients.createDefault();
  157. try {
  158. //Create httpget.
  159. HttpGet httpget = new HttpGet("http://www.baidu.com/");
  160. System.out.println("executing request " + httpget.getURI());
  161. //Execute get requests.
  162. CloseableHttpResponse response = httpclient.execute(httpget);
  163. try {
  164. //Getting response entities
  165. HttpEntity entity = response.getEntity();
  166. System.out.println("--------------------------------------");
  167. //Print response status
  168. System.out.println(response.getStatusLine());
  169. if (entity != null) {
  170. //Print response content length
  171. System.out.println("Response content length: " + entity.getContentLength());
  172. //Print response content
  173. System.out.println("Response content: " + EntityUtils.toString(entity));
  174. }
  175. System.out.println("------------------------------------");
  176. } finally {
  177. response.close();
  178. }
  179. } catch (ClientProtocolException e) {
  180. e.printStackTrace();
  181. } catch (ParseException e) {
  182. e.printStackTrace();
  183. } catch (IOException e) {
  184. e.printStackTrace();
  185. } finally {
  186. //Close the connection and release resources.
  187. try {
  188. httpclient.close();
  189. } catch (IOException e) {
  190. e.printStackTrace();
  191. }
  192. }
  193. }
  194. /**
  195. * Upload files
  196. */
  197. public void upload() {
  198. CloseableHttpClient httpclient = HttpClients.createDefault();
  199. try {
  200. HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
  201. FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
  202. StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
  203. HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
  204. httppost.setEntity(reqEntity);
  205. System.out.println("executing request " + httppost.getRequestLine());
  206. CloseableHttpResponse response = httpclient.execute(httppost);
  207. try {
  208. System.out.println("----------------------------------------");
  209. System.out.println(response.getStatusLine());
  210. HttpEntity resEntity = response.getEntity();
  211. if (resEntity != null) {
  212. System.out.println("Response content length: " + resEntity.getContentLength());
  213. }
  214. EntityUtils.consume(resEntity);
  215. } finally {
  216. response.close();
  217. }
  218. } catch (ClientProtocolException e) {
  219. e.printStackTrace();
  220. } catch (IOException e) {
  221. e.printStackTrace();
  222. } finally {
  223. try {
  224. httpclient.close();
  225. } catch (IOException e) {
  226. e.printStackTrace();
  227. }
  228. }
  229. }
  230. }</namevaluepair></namevaluepair></namevaluepair></namevaluepair>

This example uses the latest version of HttpClient 4.3. This version is quite different from the previous code style, we should pay more attention to it.


That's the same sentence... Good things to reproduce, learn one can not be less, below Turn from here

HttpClient has several points to pay attention to in its application:

Where HttpClient is generated:

ttpClient=new HttpClient();
httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

First, you must have the following two parameter settings, otherwise you will generate multiple Cookie header s to the web server
httpClient.getParams().setParameter("http.protocol.single-cookie-header",true);
httpClient.getParams().setParameter("http.protocol.content-charset","gb2312");
ArrayList headerList=new ArrayList();
Header accept=new Header("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-silverlight, */*");
headerList.add(accept);
......

httpClient.getParams().setParameter("http.default-headers",headerList);
httpClient.getParams().setParameter("http.protocol.version",HttpVersion.HTTP_1_1);
httpClient.getParams().setParameter("http.method.retry-handler",new DefaultHttpMethodRetryHandler());

Second: Where httpMethod is generated:

PostMethod postMethod =new PostMethod();
postMethod.getParams().setUriCharset("GB2312");

postMethod.setURI(new URI(url,false,"GB2312"));

client.executeMethod(postMethod);

Above can avoid sending something like "HTTP://127.0.0.1:8080/action.do?" The URI error occurred when the content = 123456 "URL.

Third: The Connection Pool Timeout Exception problem may be caused by several reasons:

1. Setting connection timeout time is not set or too small;

2. Whether the connection after request has been released;

For more information, as well as parameter settings and code writing, risks, see This article

28 March 2019, 14:39 | Views: 6028

Add new comment

For adding a comment, please log in
or create account

0 comments