Android Development implements HttpClient tool class

Source: Internet
Author: User

In Android development we often use the network connection function and the server to interact with the data, this Android SDK provides Apache httpclient to facilitate our use of various HTTP services. You can think of httpclient as a browser, with its API we can easily make Get,post requests (of course it's more than that).
For example, you can send a simple GET request and print the response result with just a few 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 (); br>    }

Why use a singleton httpclient?
This is just a demo code, and the request and response processing in the actual project is a bit more complicated and also takes into account the code's fault tolerance, but this is not the focus of this article. Note the third line of the code:

HttpClient HttpClient = new Defaulthttpclient ();

Before making an HTTP request, we created a HttpClient object. So, in a real-world project, we're likely to need HTTP communication in multiple places, and we don't need to create a new httpclient for each request. As already mentioned, HttpClient is like a small browser, for the entire application, we only need a httpclient to be enough. See here, there must be someone in the mind, this is what difficult, with a single case 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 that our application now uses the same httpclient to manage all HTTP requests, and in the event of concurrent requests, there is always a problem with multithreading. This is like our browser has only one tab but there are many users, a to Google,b to Baidu, then the browser will be busy. Fortunately, HttpClient provides APIs to create thread-safe objects that help us quickly get thread-safe "browsers".

Solving multithreading problems

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 settings
/* Timeout to fetch connections from connection pool */
Connmanagerparams.settimeout (params, 1000);
/* Connection timed out */
Httpconnectionparams.setconnectiontimeout (params, 2000);
/* Request timed out */
Httpconnectionparams.setsotimeout (params, 4000);

Set up our httpclient to support HTTP and HTTPS two modes
Schemeregistry Schreg = new Schemeregistry ();
Schreg.register ("http", Plainsocketfactory
. Getsocketfactory (), 80));
Schreg.register ("https", sslsocketfactory
. Getsocketfactory (), 443));

Use 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 timeout settings for httpclient, and then used Threadsafeclientconnmanager to create a thread-safe httpclient. The above code mentions 3 kinds of timeout settings, it is easier to confuse, so this special analysis.

3 types of timeouts for httpclient

/* Timeout to fetch connections from connection pool */
Connmanagerparams.settimeout (params, 1000);
/* Connection timed out */
Httpconnectionparams.setconnectiontimeout (params, 2000);
/* Request timed out */
Httpconnectionparams.setsotimeout (params, 4000);

The first line sets Connectionpooltimeout: This defines the time-out period for removing a connection from the ConnectionManager managed connection pool, set here to 1 seconds.
The second line sets ConnectionTimeout: This defines the time-out for establishing a connection to the server over the network. In the HttpClient package, an asynchronous thread is created to create the socket connection to the server, which is the time-out for the socket, set to 2 seconds.
The third line sets the Sockettimeout: This defines the time-out time for the socket read data, that is, how long it takes for the response data to be fetched 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 singleton httpclient object, we can encapsulate some of the commonly used code for Get and post requests and write them into our tool class. For now, I'm just 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<namevaluepair> formparams = new arraylist<namevaluepair> (); Request parameters
for (Namevaluepair p:params) {
Formparams.add (P);
}
urlencodedformentity entity = new Urlencodedformentity (Formparams,
CHARSET);
Create a 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 to write the business code for network communication. 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", "Zhang San");
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 ());
}

Android Development implements HttpClient tool class

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.