HttpClient tool for Android Development

Source: Internet
Author: User

HttpClient tool for Android Development

In Android development, we often use the network connection function to interact with the server. Therefore, the Android SDK provides Apache HttpClient to facilitate the use of various Http Services. You can think of HttpClient as a browser. Through its API, we can easily send GET and POST requests (of course, its functions are far more than that ).

For example, you only need the following lines of code to send a simple GET request and print the response result:

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.exe cute (request, new BasicResponseHandler ());

Log. v ("response text", response );

} Catch (ClientProtocolException e ){

E. printStackTrace ();

} Catch (IOException e ){

E. printStackTrace ();

}

Why use the single-instance HttpClient?

This is just a demo code. The actual request and Response Processing in the project will be more complex, and the code fault tolerance should be taken into account. However, this is not the focus of this article. Note the third line of the Code:

HttpClient httpclient = new DefaultHttpClient ();

Before sending an HTTP request, we create an HttpClient object. In actual projects, we may need to perform HTTP Communication in multiple places. At this time, we do not need to create a new HttpClient for each request. As mentioned earlier, HttpClient is like a small browser. For the entire application, we only need one HttpClient. When I see this, some people may wonder, what is the problem? use a single example !! 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 uses the same HttpClient to manage all Http requests. Once a concurrent request occurs, the problem of multithreading will certainly occur. It seems that our browser has only one tab but there are multiple users. A wants to go to google and B wants to go to baidu. Then the browser will be too busy. Fortunately, HttpClient provides an API for creating thread-safe objects, which helps us quickly obtain the thread-safe "Browser ".

Multithreading

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

/* Obtain the connection timeout value from the connection pool */

ConnManagerParams. setTimeout (partams, 1000 );

/* Connection timeout */

HttpConnectionParams. setConnectionTimeout (params, 2000 );

/* Request timeout */

HttpConnectionParams. setSoTimeout (partams, 4000 );

// Set our HttpClient to Support HTTP and HTTPS Modes

SchemeRegistry schReg = new SchemeRegistry ();

SchReg. register (new Scheme ("http", PlainSocketFactory

. GetSocketFactory (), 80 ));

SchReg. register (new Scheme ("https", SSLSocketFactory

. GetSocketFactory (), 443 ));

// Use thread-safe Connection Manager to create HttpClient

ClientConnectionManager conMgr = new ThreadSafeClientConnManager (

Params, schReg );

CustomerHttpClient = new DefaultHttpClient (conMgr, params );

}

Return customerHttpClient;

}

}

In the above getHttpClient () method, we configured some basic parameters and timeout settings for HttpClient, and then used ThreadSafeClientConnManager to create a thread-safe HttpClient. The above Code mentioned three timeout settings, which are relatively easy to mix, so this is a special analysis.

Description of HttpClient timeout

/* Obtain the connection timeout value from the connection pool */

ConnManagerParams. setTimeout (partams, 1000 );

/* Connection timeout */

HttpConnectionParams. setConnectionTimeout (params, 2000 );

/* Request timeout */

HttpConnectionParams. setSoTimeout (partams, 4000 );

Set ConnectionPoolTimeout In the first line: This defines the timeout time for retrieving connections from the connection pool managed by ConnectionManager. Set this parameter to 1 second.

The second line sets ConnectionTimeout: This defines the timeout time for establishing a connection with the server through the network. In the Httpclient package, an asynchronous thread is used to create a socket connection with the server. This is the timeout time of the socket connection, which is set to 2 seconds.

Set SocketTimeout in the third row. This defines the timeout time for the Socket to read data, that is, the time needed to wait for the response data to be obtained from the server. The value is set to 4 seconds.

The above three timeouts will throw ConnectionPoolTimeoutException, ConnectionTimeoutException, and SocketTimeoutException respectively.

Encapsulate simple POST requests

With the HttpClient object of the Singleton, We can encapsulate common GET and POST requests and write them into our tool class. Currently, I only implement the method for sending POST requests and returning response strings 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 Parameter

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 the request

HttpClient client = getHttpClient ();

HttpResponse response = client.exe cute (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, we can easily use this tool class to Write Business Code for network communication throughout the project. The following code demonstrates how to use username and password to register an account and obtain a new account ID.

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

// Prepare data

NameValuePair param1 = new BasicNameValuePair ("username", "James ");

NameValuePair param2 = new BasicNameValuePair ("password", "123456 ");

Int resultId =-1;

Try {

// Use the tool class to directly send a POST request, and the server returns json data, for example, "{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 ());

}

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.