Android Development Implementation HttpClient Tool class

Source: Internet
Author: User
Tags final getmessage http request json socket thread

In Android development, we often use the network connection function and the server data interaction, this Android SDK provides Apache httpclient to facilitate our use of a variety of HTTP services. You can think of httpclient as a browser, and through its API we can easily send out get,post requests (which, of course, are much more than that).

For example, you can send a simple GET request and print the response result with just the following lines of code:

try {

Create a default HttpClient

HttpClient httpclient = new Defaulthttpclient ();

Create a GET request

HttpGet request = new HttpGet ("www.google.com");

Send a GET request and convert the response content to a string

String response = Httpclient.execute (Request, New Basicresponsehandler ());

LOG.V ("Response text", response);

catch (Clientprotocolexception e) {

E.printstacktrace ();

catch (IOException e) {

E.printstacktrace ();

}

Why use single example httpclient?

This is just a demo of the code, the actual project in the request and response processing will be more complex, and also take into account the fault tolerance of the code, but this is not the focus of this article. Note the third line of code:

HttpClient httpclient = new Defaulthttpclient ();

Before making an HTTP request, we first created a HttpClient object. So, in a real-world project, we're probably going to need HTTP communication at multiple places, and we don't need to create a new httpclient for each request. As has been mentioned before, HttpClient is like a small browser, for the entire application, we only need one httpclient is enough. See here, someone must think, this is what difficult, with a single example Ah!! Just like this:

public class Customerhttpclient {

private static httpclient customerhttpclient;

Private Customerhttpclient () {

}

public static HttpClient Gethttpclient () {

if (null = = Customerhttpclient) {

Customerhttpclient = new Defaulthttpclient ();

}

return customerhttpclient;

}

}

Multithreading! Imagine, now our application use the same httpclient to manage all HTTP requests, once the concurrent request, then there will be multithreading problems. It is as if our browser has only one tab page but there are many users, a to Google,b to Baidu, when the browser will be busy. Fortunately, HttpClient provides an API to create thread-safe objects that help us quickly get a thread-safe "browser".

Troubleshoot multithreaded issues

public class Customerhttpclient {

private static final String CHARSET = HTTP. Utf_8;

private static httpclient customerhttpclient;

Private Customerhttpclient () {

}

public static synchronized HttpClient gethttpclient () {

if (null = = Customerhttpclient) {

Httpparams params = new Basichttpparams ();

Set some basic parameters

Httpprotocolparams.setversion (params, httpversion.http_1_1);

Httpprotocolparams.setcontentcharset (params,

CHARSET);

Httpprotocolparams.setuseexpectcontinue (params, true);

Httpprotocolparams

. Setuseragent (

Params

"mozilla/5.0" (Linux; U Android 2.2.1;en-us; Nexus one build.frg83) "

+ "applewebkit/553.1 (khtml,like Gecko) version/4.0 Mobile safari/533.1");

Timeout setting

/* Timeout for connection taking from connection pool. *

Connmanagerparams.settimeout (params, 1000);

/* Connection Timeout * *

Httpconnectionparams.setconnectiontimeout (params, 2000);

/* Request Timeout * *

Httpconnectionparams.setsotimeout (params, 4000);

Set our httpclient to support HTTP and HTTPS two modes

Schemeregistry Schreg = new Schemeregistry ();

Schreg.register (New Scheme ("http", Plainsocketfactory

. Getsocketfactory (), 80));

Schreg.register (New Scheme ("https", sslsocketfactory

. Getsocketfactory (), 443));

Using thread-safe connection management to create HttpClient

Clientconnectionmanager conmgr = new Threadsafeclientconnmanager (

params, schreg);

Customerhttpclient = new Defaulthttpclient (conmgr, params);

}

return customerhttpclient;

}

}

In the Gethttpclient () method above, we configured some basic parameters and time-out settings for httpclient, and then used Threadsafeclientconnmanager to create a thread-safe httpclient. The above code mentions 3 kinds of timeout settings, it is easy to confuse, so this special analysis.

3 kinds of timeout instructions for httpclient

/* Timeout for connection taking from connection pool. *

Connmanagerparams.settimeout (params, 1000);

/* Connection Timeout * *

Httpconnectionparams.setconnectiontimeout (params, 2000);

/* Request Timeout * *

Httpconnectionparams.setsotimeout (params, 4000);

The first line sets Connectionpooltimeout: This defines the timeout for removing connections from the ConnectionManager managed connection pool, which is set to 1 seconds.

The second line sets ConnectionTimeout: This defines the timeout for establishing a connection over the network with the server. The HttpClient package creates a socket connection to the server through an asynchronous thread, which is the timeout for the socket connection, which is set to 2 seconds.

The third line sets Sockettimeout: This defines the timeout for the socket read data, that is, the time it takes to get the response data from the server, set to 4 seconds.

The above 3 kinds of timeouts will throw connectionpooltimeoutexception,connectiontimeoutexception and Sockettimeoutexception respectively.

Encapsulates a simple POST request

With a single example of the HttpClient object, we can encapsulate some commonly used code that issues get and post requests into our tool class. I am currently only implementing a POST request and returning a response string for your reference. Add the following code to our Customerhttpclient class:

private static final String TAG = "Customerhttpclient";

public static string post (string url, Namevaluepair ... params) {

try {

Encoding parameters

List formparams = new ArrayList (); Request parameters

for (Namevaluepair p:params) {

Formparams.add (P);

}

urlencodedformentity entity = new Urlencodedformentity (Formparams,

CHARSET);

Create POST request

HttpPost request = new HttpPost (URL);

Request.setentity (entity);

Send Request

HttpClient client = Gethttpclient ();

HttpResponse response = Client.execute (request);

if (Response.getstatusline (). Getstatuscode ()!= Httpstatus.sc_ok) {

throw new RuntimeException ("request Failed");

}

Httpentity resentity = response.getentity ();

return (resentity = null)? Null:EntityUtils.toString (resentity, CHARSET);

catch (Unsupportedencodingexception e) {

LOG.W (TAG, E.getmessage ());

return null;

catch (Clientprotocolexception e) {

LOG.W (TAG, E.getmessage ());

return null;

catch (IOException e) {

throw new RuntimeException ("Connection failed", e);

}

}

Use our Customerhttpclient tool class

Now, throughout the project we can easily use the tool class for network communication business code written. The following code demonstrates how to use username and password to register an account and get a new account ID.

Final String url = "Http://yourdomain/context/adduser";

Preparing data

Namevaluepair param1 = new Basicnamevaluepair ("username", "John");

Namevaluepair param2 = new Basicnamevaluepair ("Password", "123456");

int resultid =-1;

try {

Using the tool class to issue a POST request directly, the server returns JSON data, such as "{Userid:12}"

String response = customerhttpclient.post (URL, param1, param2);

Jsonobject root = new Jsonobject (response);

ResultId = Integer.parseint (root.getstring ("userid"));

LOG.I (TAG, "New User id:" + resultid);

catch (RuntimeException e) {

Request failed or Connection failed

LOG.W (TAG, E.getmessage ());

Toast.maketext (this, E.getmessage (), toast.length_short);

catch (Exception e) {

JSON parsing error

LOG.W (TAG, E.getmessage ());

}

Related Article

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.