Android Network (4): HttpClient only-use the thread-safe Singleton mode HttpClient and the fusion of HttpClient and Application

Source: Internet
Author: User

The previous section briefly introduced the interaction between HttpClient and Tomcat server. The main character is HttpClient. There are two ways to interact with the server: get and post. So this HttpClient is similar to a browser on a computer. When I open multiple web pages, I don't need to open a web page to open a browser, but a browser opens several web pages. Corresponds to HttpClient, that is, a new HttpClient is created without a connection. Generally, we want an HttpClient in an application to be OK. Like our mobile phone or PC, no one will call to install several browsers. This article solves this problem and the code can be reused directly.

1. Think of a singleton.

Public class MyHttpClient {
Private static HttpClient mHttpClient = null;
Private static final String CHARSET = HTTP. UTF_8;
// Block the constructor and obtain the HttpClient instance only through external interfaces.
Private MyHttpClient (){


}
Public static HttpClient getHttpClient (){
If (mHttpClient = null ){
MHttpClient = new DefaultHttpClient ();
}
Return mHttpClient;
}
}

The above is the simplest Singleton that can meet your needs. But it cannot meet the multi-thread requirement, that is, when multiple Http requests are completed at the same time, it will get out of the box.

2. Thread-safe HttpClient

Fortunately, android provides a thread-safe HttpClient that can be created through ClientConnectionManager. The complete code is provided below:

Package org. yanzi. webutil; import org. apache. http. httpVersion; import org. apache. http. client. httpClient; import org. apache. http. conn. clientConnectionManager; import org. apache. http. conn. params. connManagerParams; import org. apache. http. conn. scheme. plainSocketFactory; import org. apache. http. conn. scheme. scheme; import org. apache. http. conn. scheme. schemeRegistry; import org. apache. http. conn. ssl. SSLSocketFactory; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. impl. conn. tsccm. threadSafeClientConnManager; import org. apache. http. params. basicHttpParams; import org. apache. http. params. httpConnectionParams; import org. apache. http. params. httpParams; import org. apache. http. params. httpProtocolParams; import org. apache. http. protocol. HTTP; public class MyHttpClient {private static HttpClient mHttpClient = null; private static final String CHARSET = HTTP. UTF_8; // block the constructor. You can only obtain the private MyHttpClient () {} public static HttpClient getHttpClient () {if (mHttpClient = null) of the HttpClient instance through external interfaces) {mHttpClient = new DefaultHttpClient ();} return mHttpClient;} public static synchronized HttpClient publish () {if (mHttpClient = null) {HttpParams params = new BasicHttpParams (); // set the basic parameter HttpProtocolParams. setVersion (params, HttpVersion. HTTP_1_1); HttpProtocolParams. setContentCharset (params, CHARSET); HttpProtocolParams. setUseExpectContinue (params, true); // timeout setting/* Get the connection timeout from the connection pool */ConnManagerParams. setTimeout (params, 1000);/* connection timeout */HttpConnectionParams. setConnectionTimeout (params, 2000);/* request timeout */HttpConnectionParams. setSoTimeout (params, 4000); // sets HttpClient to Support HTTp and HTTPS SchemeRegistry schReg = new SchemeRegistry (); schReg. register (new Scheme ("http", PlainSocketFactory. getSocketFactory (), 80); schReg. register (new Scheme ("https", SSLSocketFactory. getSocketFactory (), 443); // use the thread-safe Connection Manager to create javasconmgr = new ThreadSafeClientConnManager (params, schReg); mHttpClient = new DefaultHttpClient (conMgr, params );} return mHttpClient ;}}

The method getSaveHttpClient () can be used to obtain the thread-safe single-instance httpClient. The comment is detailed and can be used directly.

3. It is already perfect. Can I optimize it?

You can use Application to further optimize the creation time and other configurations of HttpClient. For more information about Application, see: link.

Create a new package named org. yanzi. application and create MyApplication. java in it. The complete code is as follows:

Package org. yanzi. application; import org. apache. http. httpVersion; import org. apache. http. client. httpClient; import org. apache. http. conn. clientConnectionManager; import org. apache. http. conn. params. connManagerParams; import org. apache. http. conn. scheme. plainSocketFactory; import org. apache. http. conn. scheme. scheme; import org. apache. http. conn. scheme. schemeRegistry; import org. apache. http. conn. ssl. SSLSocketFac Logging; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. impl. conn. tsccm. threadSafeClientConnManager; import org. apache. http. params. basicHttpParams; import org. apache. http. params. httpConnectionParams; import org. apache. http. params. httpParams; import org. apache. http. params. httpProtocolParams; import org. apache. http. protocol. HTTP; import android. app. application; public class MyAppli Cation extends Application {private HttpClient mHttpClient = null; private static final String CHARSET = HTTP. UTF_8; @ Overridepublic void onCreate () {// TODO Auto-generated method stubsuper. onCreate (); mHttpClient = this. createHttpClient () ;}@ Overridepublic void onTerminate () {// TODO Auto-generated method stubsuper. onTerminate (); this. shutdownHttpClient () ;}@ Overridepublic void onLowMemory () {// TODO Uto-generated method stubsuper. onLowMemory (); this. shutdownHttpClient ();}/** create an HttpClient instance * @ return */private HttpClient createHttpClient () {HttpParams params = new BasicHttpParams (); // set the basic parameter HttpProtocolParams. setVersion (params, HttpVersion. HTTP_1_1); HttpProtocolParams. setContentCharset (params, CHARSET); HttpProtocolParams. setUseExpectContinue (params, true); // timeout setting/* Get the connection timeout from the connection pool */ConnManagerParams. s EtTimeout (params, 1000);/* connection timeout */HttpConnectionParams. setConnectionTimeout (params, 2000);/* request timeout */HttpConnectionParams. setSoTimeout (params, 4000); // sets HttpClient to Support HTTp and HTTPS SchemeRegistry schReg = new SchemeRegistry (); schReg. register (new Scheme ("http", PlainSocketFactory. getSocketFactory (), 80); schReg. register (new Scheme ("https", SSLSocketFactory. getSocketFactory (), 443); // use the thread-safe Connection Manager to create HttpCli EntClientConnectionManager conMgr = new callback (params, schReg); HttpClient client = new DefaultHttpClient (conMgr, params); return client;} private void shutdownHttpClient () {if (mHttpClient! = Null & mHttpClient. getConnectionManager ()! = Null) {mHttpClient. getConnectionManager (). shutdown () ;}} public HttpClient getHttpClient () {return mHttpClient ;}}

Then add AndroidManifest. xml:

Android: name = "org. yanzi. application. MyApplication"

                        
                                 
              
             

Then, in the Activity, use mMyApplication = (MyApplication) getApplication ();

MMyApplication. getHttpClient () can be used to obtain HttpClient.

We can see that HttpClient is instantiated in onCreate of Application, and the Connection Manager is closed at low memory and off to release resources, which is better than writing in a common file in 2.


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.