Learn about Android's Apache interface (17)

Source: Internet
Author: User

Apache HttpClient is an open source project that provides efficient, up-to-date, feature-rich toolkit support for client HTTP programming.


In the Apache HttpClient Library, the most commonly used packages that are useful for network connections are the following:

-org.apache.http.httpresponse

-org.apache.http.client.httpclient

-org.apache.http.client.methods.httpget

-org.apache.http.impl.client.defaulfhttpclient

HttpClient httpclient=new defaulthttpclient ();


If you are retrieving information from the server, you need to use the constructor of the HttpGet class, such as the following code:

<span style= "FONT-SIZE:18PX;" >httpget request=new httpget ("http://google.com");</span>
then use the HttpGet object in the Execut () method of the HttpClient class to retrieve the HttpResponse object, such as the following code:

<span style= "FONT-SIZE:18PX;" >httpresponse Response=client.execute (Request);</span>
finally read the retrieved response, such as the following code:

<span style= "FONT-SIZE:18PX;" >bufferedreader rd = new BufferedReader (New InputStreamReader (Response.getentity (). GetContent ())); String line= ""; while ((Line=rd.readline ())!=null) {System.out.println (line);} </span>


In an Android system, you can use HttpPost and httpget to encapsulate post requests and get requests, and then use the HttpClient execut () method to send a post or GET request and return the server's response data.

The basic process for Apache networking is as follows:

1. Set the connection and read timeout time, and create a new HttpClient object, such as the following code:

<span style= "FONT-SIZE:18PX;" >httpparams httpparames=new basichttpparams (); Httpconnectionparams.setconnectiontimeout (Httpparames, 2000); Httpconnectionparams.setsotimeout (Httpparames, 2000); HttpClient httpclient=new defaulthttpclient (httpparames);</span>

2. Implement a GET request, such as the following code:

<span style= "FONT-SIZE:18PX;" >httpget get = new HttpGet (URI); if (headers! = null) {set<string> Sethead = Headers.keyset (); iterator<string& Gt Iteratorhead = Sethead.iterator (); while (Iteratorhead.hasnext ()) {String headername = Iteratorhead.next (); String headervalue = (string) headers.get (headername); Get.setheader (Headername, Headervalue);}} Response = Httpclient.execute (GET);</span>
3, the implementation of post send request processing, such as the following code:

<span style= "FONT-SIZE:18PX;" >httppost post = new HttpPost (URI); set<string> sethead = Headers.keyset ();iterator<string> iteratorhead = Sethead.iterator (); while ( Iteratorhead.hasnext ()) {String headname = Iteratorhead.next (); String headvalue = (string) headers.get (headname);p Ost.setheader (Headname, headvalue);} Contentproducer cp = new Contentproducer () {@Overridepublic void WriteTo (OutputStream outstream) throws IOException {writ Er writer = new OutputStreamWriter (OutStream, "UTF-8"); Writer.write (requestbody); Writer.flush (); Writer.close ();}}; httpentity entity = new Entitytemplate (CP);p ost.setentity (entity), response = Httpclient.execute (POST);</span>
The usual HTTP entities need to be generated dynamically when executing the context. HttpClient provides support for dynamic entities using entitytemplate entity classes and Contentproducer interfaces. Contentproducer is written in the content of the requirements to an output stream, each time the request will be generated. Therefore, creating entities through Entitytemplate is usually independent and repeatable.

4. Respond to requests via response, such as the following code:

<span style= "FONT-SIZE:18PX;" >if (Response.getstatusline (). Getstatuscode () ==200) {byte[] Result=entityutils.tobytearray (response.getEntity ( ); if (result!=null) {string Str=new string (result, "UTF-8");}} </span>
If the above code calls the ToString () method directly, it may cause some Chinese characters to be garbled, so using the Tobytearray () method, if you need to convert to a string object, You can first call the Entityutils.tobytearray () method to convert the message entity to an array of byte, and then to a string by the new string[byte[] Barray].

The above steps have realized the interaction of the network processing data.


The core function of Apache is httpclient, which makes a simple get request and prints the response result with the following lines of code:

<span style= "FONT-SIZE:18PX;" >try {//Create a default httpclienthttpclient httpclient=new defaulthttpclient ();//Create a GET request HttpGet request=new HttpGet ( URI),//Send GET request, and respond to the content converted to string Response=httpclient.execute (Request,new basicresponsehandler ());} catch (Exception e) {e.printstacktrace ();} </span>

If multiple requests need to be processed at the same time, we can use multi-threading, HttpClient provides an API for creating thread-safe objects, such as the following code:

<span style= "FONT-SIZE:18PX;" >private static final String charset=http. Utf_8;private static HttpClient httpclient;private httptest () {}public static synchronized HttpClient gethttpclient () { if (null==httpclient) {httpparams params=new basichttpparams ();//Set parameter httpprotocolparams.setversion (params, Httpversion.http_1_1); Httpprotocolparams.setcontentcharset (params, CHARSET); Httpprotocolparams.setuseexpectcontinue (params, true); Httpprotocolparams.setuseragent (params, "mozilla/5.0" (linux,u; Android 4.0;en-us, ...); /timeout for fetching connections from the connection pool connmanagerparams.settimeout (params, 2000);//Connection Timeout httpconnectionparams.setconnectiontimeout (params , 2000);//Request Timeout Httpconnectionparams.setsotimeout (params, 2000);//Set HttpClient support HTTP and HTTPS two modes Schemeregistry sr=new Schemeregistry (); Sr.register (new scheme ("http", Plainsocketfactory.getsocketfactory (), +)); Sr.register (new scheme ("https", Sslsocketfactory.getsocketfactory (), 440)); /Use thread-safe connection management to create Httpclientclientconnectionmanager ccm=new Threadsafeclientconnmanager (paramS, sr); Httpclient=new defaulthttpclient (ccm,params);} return httpClient;} </span>

In the above code, use Threadsafeclientconnmanager to create a thread-safe httpclent.






Reprint Please specify source:http://blog.csdn.net/hai_qing_xu_kong/article/details/42836319 Emotional Control _








Learn about Android's Apache interface (17)

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.