HttpClient Frustration Summary-guide

Source: Internet
Author: User

Open Commons httpclient-3.x's official website will find that this project has stopped updating, replacing it is the Apache Httpcomponents Project HttpClient and Httpcore modules, so focus on the new project.

In the HttpClient module, the latest version of the official current use is HC4.5.

First, a simple example get/post is given, but this example does not go directly to the actual scenario, and the comments are described in detail:

 Packageorg.apache.http.examples.client;Importjava.util.ArrayList;Importjava.util.List;Importorg.apache.http.HttpEntity;ImportOrg.apache.http.NameValuePair;Importorg.apache.http.client.entity.UrlEncodedFormEntity;ImportOrg.apache.http.client.methods.CloseableHttpResponse;ImportOrg.apache.http.client.methods.HttpGet;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.impl.client.CloseableHttpClient;Importorg.apache.http.impl.client.HttpClients;ImportOrg.apache.http.message.BasicNameValuePair;Importorg.apache.http.util.EntityUtils; Public classQuickStart { Public Static voidMain (string[] args)throwsException {closeablehttpclient httpclient=Httpclients.createdefault (); Try{httpget HttpGet=NewHttpGet ("Http://httpbin.org/get"); Closeablehttpresponse response1=Httpclient.execute (HttpGet); //The underlying HTTP connection is still held by the response object//The response content to is streamed directly from the network socket. //In order to ensure correct deallocation of system resources//The user must call Closeablehttpresponse#close () from a finally clause. //Please note this if response content is not fully consumed the underlying//connection cannot be safely re-used and would be shut down and discarded//By the Connection Manager.            Try{System.out.println (Response1.getstatusline ()); Httpentity entity1=response1.getentity (); //Do something useful with the response body//and ensure it is fully consumedEntityutils.consume (entity1); } finally{response1.close (); }
HttpPost HttpPost=NewHttpPost ("Http://httpbin.org/post"); List<NameValuePair> Nvps =NewArrayList <NameValuePair>(); Nvps.add (NewBasicnamevaluepair ("username", "VIP")); Nvps.add (NewBasicnamevaluepair ("Password", "Secret")); Httppost.setentity (Newurlencodedformentity (Nvps)); Closeablehttpresponse Response2=Httpclient.execute (HttpPost); Try{System.out.println (Response2.getstatusline ()); Httpentity Entity2=response2.getentity (); //Do something useful with the response body//and ensure it is fully consumedEntityutils.consume (Entity2); } finally{response2.close (); } } finally{httpclient.close (); } }}

The main comment is that, after using the Closablehttpresponse, the response cannot be reused until the consumption is finished, otherwise it will be discarded by the connection management.

Then the official text gives some more complex examples, first a link: http://hc.apache.org/httpcomponents-client-4.5.x/examples.html. In the given HttpClient example, there are various scenarios that may appear in a real-world scenario, as well as some recommended practices:

Response Handling This example demonstrates how to process HTTP responsesusingA response handler. This isThe recommended to executing HTTP requests and processing HTTP responses. This approach enables the caller to concentrate on the process of digesting HTTP responses and toDelegateThe task of system resource deallocation to HttpClient.  The use of a HTTP response handler guarantees that the underlying HTTP connection would be released back to the connection Manager automaticallyinchAll cases.  Manual Connection Release This example demonstrates how to ensure the release of the underlying HTTP connection back to The Connection Managerinch  Caseof a manual processing of HTTP responses. HttpClient Configuration This example demonstrates what to customize and configure the most common aspects of HTTP Reque St Execution and connection management. Abort Method This example demonstrates how to abort a HTTP request before its normal completion. Client Authentication This example uses HttpClient to execute an HTTP request against a target site that requires user Authentication. Request via a proxy This example demonstrates how to send an HTTP request via a proxy.  Proxy Authentication A simple example showing execution of an HTTP request over A secure connection tunneled through an Authenticating proxy. Chunk encoded POST This example shows how to stream outA request entityusingchunk encoding. Custom execution Context This example demonstrates the use of a local HTTP context populated custom attributes. Form based Logon This example demonstrates how HttpClient can is used to perform form-based logon. Threaded request execution An example that executes HTTP requests frommultiple worker threads. Custom SSL Context This example demonstrates what to create secure connections with a custom SSL context. Preemptive BASIC Authentication This example shows how HttpClient can is customized to authenticate preemptivelyusingBASIC Scheme. Generally, preemptive authentication can be considered less secure than a response to an authentication challenge and ther Efore discouraged. Preemptive DIGEST Authentication This example shows how HttpClient can is customized to authenticate preemptivelyusingDIGEST Scheme. Generally, preemptive authentication can be considered less secure than a response to an authentication challenge and ther Efore discouraged. Proxy Tunnel This example shows what to use Proxyclientinchorder to establish a tunnel through an HTTP proxy forAn arbitrary protocol. Multipart encoded Request Entity This example shows how to execute requests enclosing a MULTIPART encoded entity. Native Windows Negotiate/NTLM This example shows what to do use of Native Windows Negotiate/NTLM authentication when running on Windows OS.

These examples include the response handling interface auto-release links, manual release links, httpclient parameter configuration, stop requests, and various permissions, proxies, multi-threaded requests, HTTPS, and so on, there is really no util can fully encompass all business scenarios, Can only be based on the actual scene to adapt to more appropriate util, so it is necessary to understand the learning basic protocol and principles to write a better util.

In contrast, another module, Httpcore, is the more underlying implementation. The official explanation:

 is Set Event driven I/O model based on Java NIO.

So in a common scenario, the probability of the module is relatively small, but if you want to know the details, this part is absolutely not to be missed, and the document also shows that the module supports two IO models, java IO and Java NIO, so network IO is also needed to master the basic content.

Also give the official guide PDF of these two modules:

http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/pdf/httpclient-tutorial.pdf
http://hc.apache.org/httpcomponents-core-4.4.x/tutorial/pdf/httpcore-tutorial.pdf

A careful study will make a lot of gains.

HttpClient Frustration Summary-guide

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.