httpClient4.5 closeablehttpclient Usage

Source: Internet
Author: User

HttpClient
A Brief introduction
1. Although the Java.net package provides the basic ability to access resources through HTTP, it does not provide full flexibility and functionality that many other applications require. HttpClient is the component that seeks to make up for this gap by providing an effective, kept-up-to-date, feature-rich package to implement the latest HTTP standards and recommendations of the client.
Designed for expansion while providing strong support for the basic HTTP protocol, the HttpClient component may be the focus of developers who build HTTP client applications, such as Web browsers, Web services, and systems that leverage or extend the HTTP protocol for distributed communications.
2.HttpClient is not a browser. It is a client-side HTTP communication Implementation Library. The goal of HttpClient is to send and receive HTTP messages. HttpClient does not cache content, executes JavaScript code embedded in HTML pages, guesses content types, reformat request/redirect URIs, or other features unrelated to HTTP shipping.


Two-use
1. Execution of requests
(1) The most important feature of httpclient is the execution of HTTP methods. The execution of an HTTP method consists of one or more HTTP request/http response interchanges, usually handled internally by HttpClient. Instead, expect the user to provide a request object to execute, while HttpClient expects the transfer request to the target server and returns the corresponding response object, or throws an exception if the execution is unsuccessful.
An example of a very simple request execution process:

HttpClient HttpClient = new Defaulthttpclient (); HttpGet httpget = new HttpGet ("http://localhost/"); HttpResponse response = Httpclient.execute (HttpGet); httpentity entity = response.getentity (), if (entity! = null) {InputStream instream = entity.getcontent (); int l;byte[] tmp = New Byte[2048];while ((L = instream.read (tmp))! =-1) {}}

(2) HTTP request
All HTTP requests have a request line that combines the method name, the request URI, and the HTTP protocol version.
HttpClient supports all HTTP methods defined in the http/1.1 version: Get,head,post,put,delete,trace and options. There is a special class for each method type: Httpget,httphead,httppost,httpput,httpdelete,httptrace and httpoptions.
The requested URI is a uniform Resource locator that identifies the resource on which the request is applied. The HTTP request URI contains a protocol pattern, host name, optional port, resource path, optional query, and optional fragment.
HttpClient provides a number of tool methods to simplify the creation and modification of execution URIs.
A. Using the Uriutils tool class

Uri uri = Uriutils.createuri ("http", "www.google.com",-1, "/search", "q=httpclient&btng=google+search&aq=f &oq= ", NULL); HttpGet httpget = new HttpGet (URI); System.out.println (Httpget.geturi ());

Results: http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=
B. Query strings can also be generated from separate parameters

list<namevaluepair> qparams = new arraylist<namevaluepair> (); Qparams.add (New Basicnamevaluepair ("Q", " HttpClient ") Qparams.add (New Basicnamevaluepair (" btng "," Google Search ")), Qparams.add (New Basicnamevaluepair (" AQ ") , "F")); Qparams.add (New Basicnamevaluepair ("OQ", null)); Uri uri = Uriutils.createuri ("http", "www.google.com",-1, "/search", Urlencodedutils.format (Qparams, "UTF-8"), null); HttpGet httpget = new HttpGet (URI); System.out.println (Httpget.geturi ());

Results: http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=
(3) HTTP response
An HTTP response is a message sent back to the client by the server after receiving and interpreting the request message. The first line of the response message contains the protocol version followed by the number status code and the associated text segment.

HttpResponse response = new Basichttpresponse (HTTPVERSION.HTTP_1_1,HTTPSTATUS.SC_OK, "OK"); System.out.println (Response.getprotocolversion ()); System.out.println (Response.getstatusline (). Getstatuscode ()); System.out.println (Response.getstatusline (). Getreasonphrase ()); System.out.println (Response.getstatusline (). toString ());

Results:
http/1.1
200
Ok
http/1.1 OK

(4) Handling the header of the message
An HTTP message can contain many header information describing information properties such as content length, content type, and so on.
HttpClient provides methods for getting, adding, removing, and enumerating header information.

HttpResponse response = new Basichttpresponse (HTTPVERSION.HTTP_1_1,HTTPSTATUS.SC_OK, "OK"); Response.AddHeader (" Set-cookie "," C1=A; path=/; Domain=localhost "), Response.AddHeader (" Set-cookie "," C2=B; path=\ "/\", C3=c; domain=\ "localhost\"); Header H1 = Response.getfirstheader ("Set-cookie"); SYSTEM.OUT.PRINTLN (H1); Header H2 = Response.getlastheader ("Set-cookie"); System.out.println (H2); Header[] hs = response.getheaders ("Set-cookie"); System.out.println (hs.length);

Results:
Set-cookie:c1=a; path=/; Domain=localhost
Set-cookie:c2=b; Path= "/", c3=c; domain= "localhost"

Three use httpclient to send requests, receive responses

1. The following steps are generally required:
(1) Create a HttpClient object.
(2) Create an instance of the request method and specify the request URL. Create a HttpGet object if you need to send a GET request, or create a HttpPost object if you need to send a POST request.
(3) If you need to send request parameters, you can call HttpGet, HttpPost common setparams (Hetpparams params) method to add request parameters, for HttpPost object, you can also call 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's 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

2. Two ways to use httpclient:
(1) The first kind:

public class Httpclientexample {public static void main (String args[]) throws ioexception{List<namevaluepai        R> formparams=new arraylist<namevaluepair> ();        Formparams.add (New Basicnamevaluepair ("Account", ""));        Formparams.add (New Basicnamevaluepair ("Password", ""));        Httpentity reqentity=new urlencodedformentity (formparams, "utf-8"); Requestconfig requestconfig = Requestconfig.custom (). SetSocketTimeout (Setconnecttime).        Out (setconnectionrequesttimeout). build ();        HttpClient client = new Defaulthttpclient ();        HttpPost post = new HttpPost ("http://baidu.com");        Post.setentity (reqentity);        Post.setconfig (Requestconfig);        HttpResponse response = Client.execute (POST);            if (Response.getstatusline (). Getstatuscode () = = () {httpentity resentity = response.getentity (); String message = entityutils.tostring (resentity,"Utf-8");        SYSTEM.OUT.PRINTLN (message);        } else {System.out.println ("request Failed"); }    }}

(2) Second: This approach uses an HTTP connection pool and constructs the appropriate HTTP method using Httpbuilder

public class HttpClientExample2 {private static Poolinghttpclientconnectionmanager ConnectionManager = null;    private static Httpclientbuilder Httpbulder = null;    private static Requestconfig requestconfig = null;    private static int maxconnection = 10;    private static int defaultmaxconnection = 5;    private static String IP = "cnivi.com.cn";    private static int PORT = 80;                static {//Set HTTP status parameter Requestconfig = Requestconfig.custom (). SetSocketTimeout (5000)        . Setconnecttimeout (Setconnectionrequesttimeout). build ();        Httphost target = new Httphost (IP, PORT);        ConnectionManager = new Poolinghttpclientconnectionmanager ();        Connectionmanager.setmaxtotal (maxconnection);        Connectionmanager.setdefaultmaxperroute (defaultmaxconnection);        Connectionmanager.setmaxperroute (new Httproute (target), 20);        Httpbulder = Httpclients.custom (); Httpbulder.setconnEctionmanager (ConnectionManager);        } public static Closeablehttpclient getconnection () {closeablehttpclient httpClient = Httpbulder.build ();        HttpClient = Httpbulder.build ();    return httpClient; } public static Httpurirequest Getrequestmethod (map<string, string> Map, string url, String method) {List        <NameValuePair> params = new arraylist<namevaluepair> ();        set<map.entry<string, string>> entryset = Map.entryset ();            For (map.entry<string, string> e:entryset) {String name = E.getkey ();            String value = E.getvalue ();            Namevaluepair pair = new Basicnamevaluepair (name, value);        Params.add (pair);        } httpurirequest reqmethod = null; if ("Post". Equals (method)) {Reqmethod = Requestbuilder.post (). Seturi (URL). addparameters (PA Rams.toarray (New Basicnamevaluepair[params.size ())). Setconfig (Requestconfig). build (); } else if ("Get". Equals (method)) {Reqmethod = Requestbuilder.get (). Seturi (URL). addparamete        RS (Params.toarray (new Basicnamevaluepair[params.size ())). Setconfig (Requestconfig). build ();    } return Reqmethod; public static void Main (String args[]) throws IOException {map<string, string> Map = new Hashmap<str        ING, string> ();        Map.put ("Account", "");        Map.put ("Password", "" ");        HttpClient client = getconnection ();        Httpurirequest post = Getrequestmethod (map, "http://baidu.com", "post");        HttpResponse response = Client.execute (POST);            if (Response.getstatusline (). Getstatuscode () = = () {httpentity entity = response.getentity ();            String message = entityutils.tostring (entity, "utf-8");        SYSTEM.OUT.PRINTLN (message);        } else {System.out.println ("request Failed"); }    }}

3. Look again at an example

Import Org.apache.http.httpentity;import Org.apache.http.namevaluepair;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.conn.ssl.sslconnectionsocketfactory;import Org.apache.http.conn.ssl.sslcontexts;import Org.apache.http.conn.ssl.trustselfsignedstrategy;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;import Org.junit.Test;import Javax.net.ssl.sslcontext;import Java.io.file;import Java.io.fileinputstream;import Java.io.IOException;import Java.io.unsupportedencodingexception;import Java.security.keymanagementexception;import Java.security.KeyStore; Import Java.security.keystoreexception;import Java.security.NoSUchalgorithmexception;import Java.security.cert.certificateexception;import Java.util.arraylist;import    Java.util.list;public class httpclientexample3{@Test public void Junittest () {get ();        }/** * HttpClient connect SSL */public void SSL () {closeablehttpclient httpclient = null;            try {KeyStore Truststore = keystore.getinstance (Keystore.getdefaulttype ());            FileInputStream instream = new FileInputStream (New File ("D:\\tomcat.keystore"));            try {//load KeyStore d:\\tomcat.keystore truststore.load (instream, "123456". ToCharArray ());            } catch (Certificateexception e) {e.printstacktrace ();                } finally {try {instream.close ();  } catch (Exception ignore) {}}//trust your own CA and all self-signed certificates Sslcontext Sslcontext = Sslcontexts.custom (). Loadtrustmaterial (Truststore, New TrustselfsIgnedstrategy ()). build (); Only allow the use of the TLSV1 protocol sslconnectionsocketfactory SSLSF = new Sslconnectionsocketfactory (Sslcontext, new string[] {"T            LSv1 "}, NULL, sslconnectionsocketfactory.browser_compatible_hostname_verifier);            HttpClient = Httpclients.custom (). Setsslsocketfactory (SSLSF). build ();            Create HTTP request (get mode) httpget HttpGet = new HttpGet ("Https://localhost:8443/myDemo/Ajax/serivceJ.action");            SYSTEM.OUT.PRINTLN ("Executing request" + httpget.getrequestline ());            Closeablehttpresponse response = Httpclient.execute (HttpGet);                try {httpentity entity = response.getentity ();                System.out.println ("----------------------------------------");                System.out.println (Response.getstatusline ());                    if (Entity! = null) {System.out.println ("Response Content Length:" + entity.getcontentlength ()); System.out.println (entityutils.tostring (entity));                Entityutils.consume (entity);            }} finally {Response.close ();        }} catch (IOException e) {e.printstacktrace ();        } catch (Keymanagementexception e) {e.printstacktrace ();        } catch (NoSuchAlgorithmException e) {e.printstacktrace ();        } catch (Keystoreexception e) {e.printstacktrace ();                } finally {if (httpclient! = null) {try {httpclient.close ();                } catch (IOException e) {e.printstacktrace (); }}}}/** * Post mode submission form (Impersonate user login request) */public void Postform () {//create default Httpclien        T instance.        Closeablehttpclient httpclient = Httpclients.createdefault ();        Create HttpPost HttpPost httppost = new HttpPost ("Http://localhost:8080/myDemo/Ajax/serivceJ.action");   To 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 ());            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 {//closes the connection, freeing the resource try {httpclient.close ();            } catch (IOException e) {e.printstacktrace ();        }}}/** * Send a POST request to access the local app and return different results depending on the pass parameter */public void post () {//create default HttpClient instance.        Closeablehttpclient httpclient = Httpclients.createdefault ();        Create HttpPost HttpPost httppost = new HttpPost ("Http://localhost:8080/myDemo/Ajax/serivceJ.action");        Create parameter queue list<namevaluepair> Formparams = new arraylist<namevaluepair> ();        Formparams.add (New Basicnamevaluepair ("type", "House"));        Urlencodedformentity uefentity;            try {uefentity = new urlencodedformentity (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 {//closes the connection, freeing the resource try {httpclient.close ();        } catch (IOException e) {        E.printstacktrace (); }}}/** * Send GET request */public void get () {closeablehttpclient httpclient = httpclients.cr        Eatedefault ();            try {//create HttpGet.            HttpGet httpget = new HttpGet ("http://www.baidu.com/");            SYSTEM.OUT.PRINTLN ("Executing request" + Httpget.geturi ());            Executes a GET request.            Closeablehttpresponse response = Httpclient.execute (HttpGet);                try {//Get response entity httpentity entity = response.getentity ();                System.out.println ("--------------------------------------");                Print response Status System.out.println (Response.getstatusline ()); if (Entity! = NULL) {//Print response content length System.out.println ("Response content Lengths:" + E                    Ntity.getcontentlength ());    Print response content System.out.println ("Response content:" + entityutils.tostring (entity));            } System.out.println ("------------------------------------");            } finally {response.close ();        }} catch (Clientprotocolexception e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();            } finally {//closes the connection, freeing the resource try {httpclient.close ();            } catch (IOException e) {e.printstacktrace (); }        }    }}

You can also refer to this:

public string getresponsexmlfromurl (string url) {string result = NULL;        Closeablehttpresponse response = null;            try {response = gethttpresponse (URL);            result = Entityutils.tostring (Response.getentity (), default_charset);        Entityutils.consume (Response.getentity ());            } catch (IOException e) {log.error ("When Getresponsexmlfromurl got an error" +e.getmessage ());        Exceptions.throwexception (e);                }finally{try {if (response!=null) {response.close (); }} catch (IOException e) {log.error ("When Getresponsexmlfromurl got an error" + E.getmessage ()            );    }} return result; }public closeablehttpresponse gethttpresponse (String url) throws IOException {Poolinghttpclientconnectionmanager C        m = Httpconnectionmanager.getinstance ();        int timeout = 5; Requestconfig Requestconfig = RequeStconfig.custom (). Setconnecttimeout (Timeout * $). SetSocketTimeout (Timeout * 1000 *        ). build ();    Return Httpclientcreator (Cm,requestconfig). Execute (new HttpGet (URL)); }public closeablehttpclient httpclientcreator (Poolinghttpclientconnectionmanager cm,RequestConfig RequestConfig) {i F (Null! = Requestconfig) {return Httpclients.custom (). Setconnectionmanager (cm). Setdefaultrequestconfig (REQUESTC        Onfig). SetProxy (New Httphost (Proxyurl, integer.valueof (ProxyPort))). build (); } else {return Httpclients.custom (). Setconnectionmanager (cm). SetProxy (New Httphost (Proxyurl, integer.valueof (p        Roxyport)). Build (); }

Reference: http://www.cnblogs.com/lyy-2016/p/6388663.html

httpClient4.5 closeablehttpclient Usage

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.