Study and application of the httpclient of Java4android

Source: Internet
Author: User

In Java development, the inevitable need to deal with HTTP. Regardless of our Thunder animation or I led the "Search Bud" Android client development, all need to use to HTTP and server to deal with. Although Java also provides an interface for HTTP, I understand that more companies are using Apache's httpclient to develop, not only because it is flexible and powerful, but also convenient.

Today, we learn the basic knowledge of httpclient.

The basics of HTTP are not reviewed here. Suggest you go to see an authoritative production "http authoritative guide", add a slightly expensive, 109 yuan, however, I bought, because the classic book, or more prepared, I did not see how, but encountered problems can be turned.


Talk less, cut to the chase.

We send an HTTP request in HttpClient, which generally follows the process pattern:

1. Create the 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 the HttpGet, HttpPost common setparams (Hetpparams params) method to add the request parameters, and for HttpPost objects, 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 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.

The code examples are as follows:

Closeablehttpclient httpclient = Httpclients.createdefault (); HttpGet httpget = new HttpGet ("http://localhost/"); Closeablehttpresponse response = Httpclient.execute (httpget); try {<...>} finally {response.close ();}

Request:

HttpClient supports all commands for all http/1.1, including: Get,head,post,put,delete,trace and Options. And there are separate classes: Httpget,httphead,.... Wait a minute.

The request URI is a Uniform resource identifier that identifies the resource you want to request. It generally contains protocol scheme, host name, optional port, resource path,optional query, optional fragment this information. Such as:

HttpGet httpget = new HttpGet ("Http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f &oq= ");
A better way to construct the above URIs is to use UriBuilder. Specific as follows:

Uri uri = new UriBuilder (). SetScheme ("http"). Sethost ("www.google.com"). SetPath ("/search"). Setparameter ("Q", " HttpClient "). Setparameter (" btng "," Google Search "). Setparameter (" AQ "," F "). Setparameter (" OQ "," "). Build (); HttpGet httpget = new HttpGet (URI);


Reply:

The reply (response) is the server's response to the client. The reply in HttpClient is HttpResponse.

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 ());
Output:
http/1.1200okhttp/1.1 OK

Message header:

If you are familiar with HTTP packets, you know that an HTTP message is made up of three parts: the start line that describes the message, the header of the property containing the header, and optionally, the body part of the data.

HttpClient An example of a head:

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);

The result of the output:

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

HTTP entity: There are three entities, streamed,self-contained and wrapping in HttpClient. Their differences are differentiated when we use them, in general, stream objects are suitable for receiving streaming data, and self-contained self-contained scenarios that are suitable for repeatable reads. Wrapping is a wrapper over an existing entity. Here is an example of using an entity:
Closeablehttpclient httpclient = Httpclients.createdefault (); HttpGet httpget = new HttpGet ("http://localhost/"); Closeablehttpresponse response = Httpclient.execute (httpget); try {httpentity entity = response.getentity (); if (Entity!) = null) {InputStream instream = entity.getcontent (); try {//do something useful} finally {instream.close ();}}} finally {response.close ();}

Use of the entity:
Closeablehttpclient httpclient = Httpclients.createdefault (); HttpGet httpget = new HttpGet ("http://localhost/"); Closeablehttpresponse response = Httpclient.execute (httpget); try {httpentity entity = response.getentity (); if (Entity!) = null) {Long len = Entity.getcontentlength (); if (len! =-1 && len < 2048) {System.out.println (entityutils.tost Ring (entity)); else {//Stream content out}}} finally {Response.close ();}

So, how to produce an entity: There are many kinds of entities, so HttpClient also provides several classes that produce entities, each of which produces corresponding entities. Stringentity,bytearrayentity,inputstreamentity and Fileentity, which produce string, byte array, input stream, file, respectively. An example of a fileentity is as follows:
File File = new file ("Somefile.txt"); fileentity entity = new Fileentity (file,contenttype.create ("Text/plain", "UTF-8"); HttpPost HttpPost = new HTTPP

Form: HttpClient also provides features similar to HTTP forms, such as user login page, user name and password.
list<namevaluepair> formparams = new arraylist<namevaluepair> (); Formparams.add (New BasicNameValuePair (" Param1 "," value1 ")); Formparams.add (New Basicnamevaluepair (" param2 "," value2 ")); urlencodedformentity entity = new Urlencodedformentity (Formparams, consts.utf_8); HttpPost HttpPost = new HttpPost ("http://localhost/handler.do"); httppost.setentity (entity);
will produce the following effects:
Param1=value1&m2=value2


In the end, I give a package of our get and post methods for HttpClient, where the code will relate to the elements that we talked about earlier.
 Private InputStream httpget (string url, string cookie) {HttpGet httpget = new HttpGet (URL);        Httpget.setheader ("accept-encoding", "gzip,deflate"); if (! (        Textutils.isempty (cookie))) {Httpget.setheader ("cookie", cookie);    } return Httpdo (httpget, URL, null); } private InputStream httppost (String URL, map<string, string> headers, map<string, object> para        MS) {HttpPost post = new HttpPost (URL);        Httpentity entity = NULL;        Object value = Params.get (post_entity);        if (value instanceof httpentity) {entity = (httpentity) value;            } else {list<namevaluepair> pairs = new arraylist<namevaluepair> ();                For (map.entry<string, object> e:params.entryset ()) {value = E.getvalue ();                    if (value! = null) {Log.debug ("param=" + e.getkey () + ":" + value.tostring ()); Pairs.add (New BasicNamevaluepair (E.getkey (), value. toString ()));            }} try {entity = new urlencodedformentity (pairs, "UTF-8");             } catch (Unsupportedencodingexception E1) {Log.warn ("Unsupportedencodingexception err={}", e1.tostring ()); }} if (headers! = null &&!headers.containskey ("Content-type")) {Headers.pu        T ("Content-type", "application/x-www-form-urlencoded;charset=utf-8");        } post.setentity (entity);    Return Httpdo (post, URL, headers); } private InputStream Httpdo (httpurirequest hr, String URL, map<string, string> headers) {Inpu        TStream in = null; if (headers! = null) {for (String Name:headers.keySet ()) {Hr.addheader (name, Headers.get (nam            e));        }} defaulthttpclient client = Getclient ();        HttpResponse response; Try {response = Client.execute (HR);            int statusCode = Response.getstatusline (). Getstatuscode ();            Log.debug ("this={}, Response code={}", this, statusCode);                if (StatusCode = = HTTPSTATUS.SC_OK) {httpentity entity = response.getentity ();                    if (null! = entity) {Header Header = entity.getcontentencoding (); if (header = null && header.getvalue (). Equals ("gzip")) {in = new Gzipinputstream (ENTITY.G                    Etcontent ());                    } else {in = Entity.getcontent (); }}} else {Log.warn ("Request HTTP resource failed.            statuscode={} url={} ", StatusCode, URL); }} catch (IOException e) {log.warn ("Request HTTP resource failed.        {}, err={} ", this, e.tostring ()); } catch (IllegalStateException e) {log.warn ("Request HTTP resource failed.        url={} err={} ", URL, e.tostring ());    } return in;        } private static Defaulthttpclient getclient () {httpparams httpparams = new Basichttpparams ();        Httpconnectionparams.setconnectiontimeout (Httpparams, connection_timeout);        Httpconnectionparams.setsotimeout (Httpparams, so_timeout);        Http://stackoverflow.com/questions/5358014/android-httpclient-oom-on-4g-lte-htc-thunderbolt        Httpconnectionparams.setsocketbuffersize (Httpparams, 8192);    return new Defaulthttpclient (Httpparams); }

Time is limited, so far today.












Study and application of the httpclient of Java4android

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.