I. Introduction
Httpclient is a sub-project under Apache Jakarta common. It is used to provide an efficient, up-to-date, and function-rich client programming toolkit that supports http protocol. It also supports the latest versions and suggestions of HTTP protocol. Httpclient has been applied to many projects. For example, the other two open-source projects cactus and htmlunit on Apache Jakarta both use httpclient.
Httpclient is just as amazing as luence, and each version changes a lot. The latest version has reached 4.3.5 and is not compatible with 3.x since 4.x. Someone once tested that version 3.x is faster than version 4.X, but you have to consider that multithreading is now supported.
Latest: http://hc.apache.org/downloads.cgi
Ii. Features
1. Based on standard and pure Java language. Http1.0 and http1.1 are implemented.
2. Implement all HTTP methods (get, post, put, delete, Head, options, and trace) in a scalable object-oriented structure ).
3. HTTPS is supported.
4. Establish a transparent connection through the HTTP proxy.
5. Use the connect method to establish a tunnel HTTPS connection through the HTTP proxy.
6. Basic, digest, ntlmv1, NTLMv2, ntlm2 session, snpnego/Kerberos authentication scheme.
7. Plug-in-type custom authentication solution.
8. The portable and reliable socket factory makes it easier to use third-party solutions.
9. The Connection Manager supports multi-threaded applications. You can set the maximum number of connections and the maximum number of connections for each host to discover and disable expired connections.
10. automatically process the cookie in set-Cookie.
11. Plug-in-type custom cookie policy.
12. The output stream of the request can avoid directly buffering the content in the stream to the socket server.
13. The response input stream can effectively directly read the corresponding content from the socket server.
14. Use keepalive in http1.0 and http1.1 to maintain persistent connections.
15. Get the response code and headers sent by the server directly.
16. Set the connection timeout capability.
17. Experimental support for http1.1 response caching.
18. You can obtain the source code for free based on Apache license.
The most basic function of httpclient is to execute the HTTP method. You only need to provide the HTTP request object, and httpclient will send the HTTP request to the target server and receive the response from the server. JDK itself does not have the same urlconnection function. But from the features described above, httpclient is more powerful! In this article, we will introduce the two most basic methods for HTTP request execution in httpclient: Get and post.
Iii. Method Introduction
Let's not talk about it. First, let's look at the code. Note that it is very different from the previous 3.x version. You have to import these jar packages:
650) This. width = 650; "src =" http://s3.51cto.com/wyfs02/M01/45/84/wKiom1PojRexfPHtAAG69q_C4dI572.jpg "Title =" qq 40811172839.jpg "alt =" wkiom1pojrexfphtaag69q_c4di572.jpg "/>
These jar packages in the Lib folder in the httpcomponents-client-4.3.5, the article below also provides resources to download ~
Import Java. io. ioexception; import Java. io. unsupportedencodingexception; import Java. util. arraylist; import Java. util. list; import Org. apache. HTTP. httpentity; import Org. apache. HTTP. namevaluepair; import Org. apache. HTTP. parseexception; import Org. apache. HTTP. client. clientprotocolexception; 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. impl. client. closeablehttpclient; import Org. apache. HTTP. impl. client. httpclients; import Org. apache. HTTP. message. basicnamevaluepair; import Org. apache. HTTP. util. entityutils; public class httpclienttest {/*** get Method */Public void httpget () {closeablehttpclient httpclient = httpclients. c Reatedefault (); try {// create httpget. httpget = new httpget ("http ://...... "); System. out. println ("executing request" + httpget. geturi (); // executes the GET request. closeablehttpresponse response = httpclient.exe cute (httpget); try {// get the response entity httpentity entity = response. getentity (); system. out. println ("------------------------------------"); // print the response status system. out. println (response. getstatusline (); If (entity! = NULL) {// print the response Content Length System. out. println ("response Content Length:" + entity. getcontentlength (); // print the response content system. out. println ("response content:" + entityutils. tostring (entity);} system. out. println ("------------------------------------");} finally {response. close () ;}} catch (clientprotocolexception e) {e. printstacktrace ();} catch (parseexception e) {e. printstacktrace ();} catch (ioexcep Tion E) {e. printstacktrace ();} finally {// close the connection and release the resource try {httpclient. close ();} catch (ioexception e) {e. printstacktrace () ;}}/ *** POST method (Form submission) */Public void httppostform () {// create the default httpclient instance. closeablehttpclient httpclient = httpclients. createdefault (); // create httppost = new httppost ("http ://............ "); // Create a parameter queue list <namevaluepair> formparams = new arraylist <namevaluepair> (); formparams. add (New basicnamevaluepair ("username", "admin"); formparams. add (New basicnamevaluepair ("password", "123456"); urlencodedformentity uefentity; try {uefentity = new urlencodedformentity (formparams, "UTF-8"); httppost. setentity (uefentity); system. out. println ("executing request" + httppost. geturi (); closeable Httpresponse response = httpclient.exe cute (httppost); try {httpentity entity = response. getentity (); If (entity! = NULL) {system. out. println ("------------------------------------"); system. out. println ("response content:" + entityutils. tostring (entity, "UTF-8"); system. out. println ("--------------------------------------") ;}} finally {response. close () ;}} catch (clientprotocolexception e) {e. printstacktrace ();} catch (unsupportedencodingexception E1) {e1.printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} finally {// close the connection and release the resource try {httpclient. close ();} catch (ioexception e) {e. printstacktrace ();}}}}
Summary:
1. Create an httpclient object.
2. Create an instance of the Request Method and specify the request URL. (Httpget and httppost objects)
3. If you need to send request parameters, you can use the setparams (hetpparams Params) method of httpget and httppost to add request parameters. The httppost object can also use the setentity (httpentity entity) method to set request parameters.
4. Call the execute (httpurirequest request) of the httpclient object to send a request. This method returns an httpresponse.
5. call the getallheaders () and getheaders (string name) Methods of httpresponse to obtain the response header of the server. Call the getentity () method of httpresponse to obtain the httpentity object, this object encapsulates the response content of the server. The program can get the server response content through this object.
6. Release the connection. The connection must be released no matter whether the execution method is successful or not.
4. httpclient sends HTTPS requests
Sometimes we have to send HTTPS requests for security considerations. Of course there are many methods, and I am here for your reference.
Import Java. security. keymanagementexception; import Java. security. keystoreexception; import Java. security. nosuchalgorithmexception; import Java. security. cert. certificateexception; import Java. security. cert. x509certificate; import javax.net. SSL. sslcontext; import Org. apache. HTTP. conn. SSL. sslconnectionsocketfactory; import Org. apache. HTTP. conn. SSL. sslcontextbuilder; import Org. apache. HTTP. conn. SSL. truststrategy; import Org. apache. HTTP. impl. client. closeablehttpclient; import Org. apache. HTTP. impl. client. httpclients; public class httpclientutil {public static closeablehttpclient createsslclientdefault () {try {sslcontext = new sslcontextbuilder (). loadtrustmaterial (null, new truststrategy () {// trust all public Boolean istrusted (x509certificate [] Chain, string authtype) throws certificateexception {return true ;}}). build (); sslconnectionsocketfactory sslsf = new sslconnectionsocketfactory (sslcontext); Return httpclients. custom (). setsslsocketfactory (sslsf ). build ();} catch (keymanagementexception e) {e. printstacktrace ();} catch (nosuchalgorithmexception e) {e. printstacktrace ();} catch (keystoreexception e) {e. printstacktrace ();} return httpclients. createdefault ();}}
Well, write her in the util tool class. If you want to send an HTTPS request
Closeablehttpclient httpclient = httpclients. createdefault (); replace the method for creating an instance:
Closeablehttpclient httpclient = httpclientutil. createsslclientdefault (); next, how to write it as is.
V. References
Tracing network: http://www.yeetrack.com /? P = 773 (Comprehensive Analysis of httpclient4.x)
Vi. Conclusion
This article briefly introduces httpclient. Of course, its functions are far more than that. It will be further studied in the future. If there are any deficiencies in this article, I hope to point out them. Persistence is a kind of spirit, and sharing is a kind of happiness!
This article is from the "Learn and think" blog, please be sure to keep this source http://linhongyu.blog.51cto.com/6373370/1538672