"Turn" Pro Android Learning Note (71): HTTP Service (5): Multithreaded call HttpClient

Source: Internet
Author: User

Directory (?) [-]

    1. Sync issues for applying shared httpclient objects
    2. Create shared HttpClient code
      1. Create a Shared object
      2. To create a shareable HttpClient object
    3. Using code that shares a HttpClient object
      1. Base Code
      2. Modifying the parameters of an HTTP connection
    4. Using a common Appcliation object

The article reproduced only for non-commercial nature, and can not be accompanied by virtual currency, points, registration and other conditions, reprint must indicate the source: http://blog.csdn.net/flowingflying/

Sync issues for applying shared httpclient objects

In the previous example, HttpClient is used only for a request, and we can create a shared httpclient object for the entire app. There is a problem with multithreading, and HttpClient has already considered this problem by creating a Defaulthttpclient object that uses Threadsafeclientconnmanager.

Create shared HttpClient codeCreate a Shared object

The way to create a shared object is generic, as follows:

public class Customhttpclient {
private static HttpClient client = NULL;//Apply Shared objects

/* Use private constructor, prohibit other classes by customhttpclient xx = new Customhttpclient (); This way, create an object that ensures the uniqueness of the object */
Private Customhttpclient(){
}
/ * Gets the object through a static call, created when the first call is empty */
public static synchronized HttpClient getcustomhttpclient () {

if (client = = null) {
/* If the object is empty, create the */
... ...
}
return client;
}
/ * Prohibit clone, also guarantee the uniqueness of the object * *
Public Object Clone () throws clonenotsupportedexception{
throw new Clonenotsupportedexception ();
}

}

To create a shareable HttpClient object

The following gives the omitted part of the above code, when the object is empty, the code that creates the HttpClient object, in order to facilitate understanding, the code from can look forward.

//"2.1" Set HTTP parameters
Httpparams params = new Basichttpparams ();

/*setting Httpparam is the basic parameteris actually the message header that corresponds to the HTTP request. Three of them are well understood, with a focus on some setuserexpectcontinue. Generally set to Flase, set to true is usually to pass the request message very large (example carrying large files), and the server may require authentication, we do not want to pass this large file, only to receive the server's refusal. HTTP is a TCP streaming mode when the server receives the requested header field that is Except:100-continue, does not wait for the entire request, returns a continue answer to continue reading, or gives a deny request (final Status code, such as 4xx). For details, refer to: http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3 */
httpprotocolparams.setversion(params, httpversion.http_1_1);
Httpprotocolparams.setcontentcharset(params, HTTP.) Default_content_charset);
httpprotocolparams.setuseexpectcontinue(params, true);
httpprotocolparams.setuseragent(Params, "mozilla/5.0 (Linux; U Android 2.2.1; En-us; Nexus one build/frg83) "+
"applewebkit/533.1 (khtml, like Gecko) version/4.0 Mobile safari/533.1");
/ * Set the time-out period. Timeout exceptions are IOException, in addition Clientprotocolexception is also with IOException*/
Gets the time of the connection from Clientconnectionmanager, which is the timeout setting for getting the connection from the connection pool, which can occur only if all connections to the connection pool are in use. Timeout will throw out connectionpooltimeoutexception. A httpclient corresponding manager, there is a connection pool, there are multiple connections (sockets), which is my guess of its architecture.
Connmanagerparams.settimeout (params, 1000);
This is the timeout setting for connecting to the remote Web server, and the timeout is thrown out connecttimeoutexception
Httpconnectionparams.setconnectiontimeout (params, 5000);//Connection timed out
This is the setting that waits up to a response after the request message is sent, and the timeout is thrown out sockettimeoutexception
Httpconnectionparams.setsotimeout (params, 10000);//socket timeout
//"2.2" setting sheme, registering HTTP and HTTPS
Schemeregistry Schreg = new Schemeregistry ();
Schreg.register (New Scheme ("http", Plainsocketfactory.getsocketfactory (), 80));
Schreg.register (New Scheme ("https", Plainsocketfactory.getsocketfactory (), 443));

//"2" Clientconnectionmanager is used to manage HTTP connections, we use the same client to process requests, to ensure the use of multithreaded security, using Threadsafeclientconnmanager, is a thread-safe connection pool. If multiple threads request at the same time, or there is a delay condition.
Clientconnectionmanager conmgr = new Threadsafeclientconnmanager (Params,schreg);
"1" takes Threadsafeclientconnmanager as the manager parameter, creating a HttpClient object that can be synchronously protected for multithreaded calls
Client = new Defaulthttpclient (conmgr,params);

Code base code for using shared HttpClient objects

Here is the code for the activity to invoke this shared httpclient:

public class Httpactivity extends activity{
Private HttpClient client = null;

protected void OnCreate (Bundle savedinstancestate) {
...//ui processing, etc.
client = Customhttpclient.getcustomhttpclient ();
Gethttpcontent ();
}

private void Gethttpcontent () {
try{
HttpGet request = new HttpGet ("http://www.google.com");
/* When dealing with response, use Android-provided basicresponsehandler:handleresponse (HttpResponse response), Returns the response Body as a String.  If the response was successful (a 2XX status code). */
String page =Client.execute (request,new basicresponsehandler ());
LOG.D ("pro-http", page);
}catch (IOException e) {
E.printstacktrace ();
}
}
}

Modifying the parameters of an HTTP connection

We have set the relevant HTTP connection parameters when we created the httpclient, actually corresponds to the message header in the HTTP request message, if a request needs to modify these parameters, the public properties should not be modified, otherwise it will affect other requests. Instead, it is set by specific request requests. The code example is as follows:

We set an empty address of the intranet to determine if the parameter modification was successful by the time the connection timeout occurred in Logcat
HttpGet request = new HttpGet ("http://192.168.0.199");

Reading the httpclient parameter settings
Httpparams Clientparams=client.getparams ();
LOG.D ("Pro-http", Log.d (string.valueof (httpconnectionparams.getconnectiontimeout));//Display as 5000
LOG.D ("Pro-http", String.valueof (Httpconnectionparams.getsotimeout (Clientparams)));//Display as 10000

//The original set connection timeout is 5 seconds, the following will reset the parameter, set to 20 seconds, we set the new parameter in request, will not affect other requests
Httpparams params = Request.getparams ();
Httpconnectionparams.setconnectiontimeout (params, 20000);//20s
Request.setparams (params);
LOG.D ("Pro-http", string.valueof (Httpconnectionparams.getconnectiontimeout (params)));//Display 20000
LOG.D ("Pro-http", string.valueof (Httpconnectionparams.getsotimeout (params))); Showing 0

Using a common Appcliation object

For apps to share the same object globally, reminiscent of the Appclication object, there is a Application object for Android apps that can be Getapplicationcontext () in the app or getapplication () to obtain. If we don't have a custom application class, we're using android.app.Application. We can of course put the HttpClient object in a custom application class, but it is not advisable to have the application class become complex for this trivial matter.

Here, we will explore the custom appcliation. As simple as creating a custom application class, there is a system for creating the Application object. Below we add a counter to the custom application.

Import android.app.Application;

public class CustomApplication extends application{
private int counter = 0;

public int Getcounter () {
return ++counter;
}
}

All components of the app can be application objects, and are the only one. As seen from the running results, there are several ways to get this object.

customapplication app = (customapplication) getapplication ();
LOG.D ("Pro-wei", "Counter:" + app.getcounter ()); Test if the counter is normal.
LOG.D ("Pro-wei", "Context:" + app);
LOG.D ("Pro-wei", "Context:" + App.getapplicationcontext ()); Test the other ways to get the app class
LOG.D ("Pro-wei", "Context:" + Getapplicationcontext ()); Test the other ways to get the app class

The example code covered in this blog post can be downloaded in the Pro Android Learning: Http Service Small example.

RELATED Links: My Android development related articles

"Turn" Pro Android Learning Note (71): HTTP Service (5): Multithreaded call HttpClient

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.