Use of the Get and post methods in httpclient-4.3.x

Source: Internet
Author: User
Tags response code

Transferred from: http://linhongyu.blog.51cto.com/6373370/1538672

First, Introduction

HttpClient is a sub-project under Apache Jakarta common to provide an efficient, up-to-date, feature-rich client programming toolkit that supports the HTTP protocol, and it supports the latest versions and recommendations of the HTTP protocol. HttpClient has been used in many projects, such as the two other open source projects that are famous on Apache Jakarta Cactus and Htmlunit use httpclient.

HttpClient this goods and luence as there are wonderful, each version of the changes are very large. The latest version is now at 4.3.5, which is incompatible with the 3.X version from 4.X onwards. Someone has tested that the 3.x version is faster than 4.x, but you have to consider that people now support multithreading.

Latest Version: http://hc.apache.org/downloads.cgi

Second, the characteristics

1. Based on the standard, pure Java language. Http1.0 and Http1.1 are implemented.

2. The full HTTP method (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) is implemented with the extensible object-oriented architecture.

3. Support HTTPS protocol.

4. Establish a transparent connection through an HTTP proxy.

5. Use the Connect method to establish an HTTPS connection to the tunnel through an HTTP proxy.

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, snpnego/kerberos Certification Scheme.

7. Plug-in custom authentication scheme.

8. A portable and reliable socket factory makes it easier to use third-party solutions.

9. Connection Manager supports multithreaded applications. Supports setting the maximum number of connections, supports setting the maximum number of connections per host, and discovers and closes expired connections.

10. Automatic processing of cookies in Set-cookie.

11. Plug-in custom cookie policy.

The output stream of request can prevent the content in the stream from being buffered directly to the socket server.

The input stream of response can effectively read the content directly from the socket server.

14. Use KeepAlive to maintain a persistent connection in http1.0 and http1.1.

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

16. The ability to set the connection timeout.

17. Experimental support http1.1 response caching.

18. The source code is available for free based on Apache License.

The most basic function of httpclient is to execute the HTTP method, the user only needs to provide the HTTP request object, HttpClient will send the HTTP request to the target server, and receive the response of the server. The JDK itself does not have the same functional approach that comes with a urlconnection, but from the features described above, httpclient is more powerful! In this paper, we will introduce the two most basic methods of executing HTTP requests in HttpClient--get and the Post method.

Iii. Introduction of methods

Needless to say, first on the code, to note that there is a big difference from the previous 3.x version, but also to import these several jar packages:

Four, demo

Importjava.io.IOException;Importjava.io.UnsupportedEncodingException;Importjava.util.ArrayList;Importjava.util.List;Importorg.apache.http.HttpEntity;ImportOrg.apache.http.NameValuePair;Importorg.apache.http.ParseException;Importorg.apache.http.client.ClientProtocolException;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 classHttpclienttest {/*** Get Method*/     Public voidHttpGet () {closeablehttpclient httpclient=Httpclients.createdefault (); Try {              //Create a httpget. HttpGet HttpGet =NewHttpGet ("http://...")); System.out.println ("Executing request" +Httpget.geturi ()); //executes a GET request. Closeablehttpresponse response =Httpclient.execute (HttpGet); Try {                  //Get response Entityhttpentity entity =response.getentity (); System.out.println ("--------------------------------------"); //Print response StatusSystem.out.println (Response.getstatusline ()); if(Entity! =NULL) {                      //Print response content lengthSystem.out.println ("Response Content Length:" +entity.getcontentlength ()); //Print Response ContentSystem.out.println ("Response content:" +entityutils.tostring (entity)); } System.out.println ("------------------------------------"); } finally{response.close (); }          } Catch(clientprotocolexception e) {e.printstacktrace (); } Catch(ParseException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally {              //Close the connection and release the resource            Try{httpclient.close (); } Catch(IOException e) {e.printstacktrace (); }          }      }           /*** Post method (form submission)*/     Public voidHttppostform () {//creates a default HttpClient instance. Closeablehttpclient httpclient =Httpclients.createdefault (); //Create HttpPostHttpPost HttpPost =NewHttpPost ("http://...")); //To create a parameter queueList<namevaluepair> Formparams =NewArraylist<namevaluepair>(); Formparams.add (NewBasicnamevaluepair ("username", "admin")); Formparams.add (NewBasicnamevaluepair ("Password", "123456"));          Urlencodedformentity uefentity; Try{uefentity=NewUrlencodedformentity (Formparams, "UTF-8");              Httppost.setentity (uefentity); System.out.println ("Executing request" +Httppost.geturi ()); Closeablehttpresponse Response=Httpclient.execute (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 of Usage methods:

1. Create the 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 call the HttpGet, HttpPost common setparams (Hetpparams params) method to add the request parameters. The HttpPost object can also call the setentity (httpentity entity) method to set the request parameters.

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

5. Call HttpResponse's Getallheaders (), Getheaders (String name) and other methods to get the server's response header; call HttpResponse getentity () The Httpentity method gets the object that wraps the server's response content. This object is used by the program to obtain the server's response content.

6. Release the connection. The connection must be released regardless of the success of the execution method.

V. HttpClient sending HTTPS requests

Sometimes for security reasons, we have to send HTTPS requests. Of course there are a lot of methods, I am only for reference.

Importjava.security.KeyManagementException;Importjava.security.KeyStoreException;Importjava.security.NoSuchAlgorithmException;Importjava.security.cert.CertificateException;Importjava.security.cert.X509Certificate;ImportJavax.net.ssl.SSLContext;Importorg.apache.http.conn.ssl.SSLConnectionSocketFactory;ImportOrg.apache.http.conn.ssl.SSLContextBuilder;ImportOrg.apache.http.conn.ssl.TrustStrategy;Importorg.apache.http.impl.client.CloseableHttpClient;Importorg.apache.http.impl.client.HttpClients;  Public classHttpclientutil { Public Staticcloseablehttpclient Createsslclientdefault () {Try{sslcontext Sslcontext=NewSslcontextbuilder (). Loadtrustmaterial (NULL,NewTruststrategy () {//Trust all                  Public Booleanistrusted (x509certificate[] chain, String authtype)throwscertificateexception {return true;             }}). Build (); Sslconnectionsocketfactory SSLSF=Newsslconnectionsocketfactory (Sslcontext); returnHttpclients.custom (). Setsslsocketfactory (SSLSF). build (); } Catch(keymanagementexception e) {e.printstacktrace (); } Catch(nosuchalgorithmexception e) {e.printstacktrace (); } Catch(keystoreexception e) {e.printstacktrace (); }         returnHttpclients.createdefault (); } }

Well, write her in the Util tool class, and then if you want to send an HTTPS request, put the original GET, POST request

Closeablehttpclient httpclient = Httpclients.createdefault (); The method to create the instance is replaced by:

Closeablehttpclient httpClient = Httpclientutil.createsslclientdefault (); The next thing to do is write it as is.

V. References

Easy-to-trace network: http://www.yeetrack.com/?p=773 (more comprehensive on httpclient4.x analysis)

Vi. Conclusion

This article is just a rough introduction to the next httpclient. Of course, its function is much more than that. Further research is still to be provided, if there are deficiencies in the article, also hope to point out. Persistence is a kind of spirit, sharing is a kind of happiness!

Use of the Get and post methods in httpclient-4.3.x

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.