Android Network (4): HttpClient The only way----use thread-safe singleton mode httpclient, and httpclient and application fusion

Source: Internet
Author: User

The interaction between the httpclient and the Tomcat server is briefly described above, and the protagonist is HttpClient, and then it interacts with the server in two ways: Get and post. So this httpclient is similar to the browser used on the computer. When I open multiple Web pages, I do not need to open a Web page to open a browser, but a browser open several pages. Corresponds to HttpClient, which means that a new httpclient is not required to connect once. In general, we want an application to be a httpclient on the OK, like our phone or PC, no one will be whistling several browsers. This article solves this problem, and the code can be reused directly from the past.

1, naturally think of a single case.

public class Myhttpclient {
private static HttpClient mhttpclient = null;
private static final String CHARSET = HTTP. Utf_8;
The constructor is closed and the HttpClient instance can only be obtained through the external interface.
Private Myhttpclient () {


}
public static HttpClient Gethttpclient () {
if (mhttpclient = = null) {
Mhttpclient = new Defaulthttpclient ();
}
return mhttpclient;
}
}

The simplest of these is the simple one, which really satisfies the need. But it can't meet the requirement of multithreading, that is, when multiple HTTP requests are completed at the same time, the egg is gone.

2, Thread-safe httpclient

Fortunately, Android has provided a thread-safe httpclient that can be created by Clientconnectionmanager. The complete code is posted 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;//the constructor, only the external interface can be used to get the HttpClient instance private myhttpclient () {}public static HttpClient gethttpclient () {if ( Mhttpclient = = null) {Mhttpclient = new Defaulthttpclient ();} return mhttpclient;} public static synchronized HttpClient getsavehttpclient () {if (mhttpclient = = null) {Httpparams params = new Basichttpparams ();//Set Basic parameters Httpprotocolparams.setversion (params, httpversion.http_1_1); Httpprotocolparams.setcontentcharset (params, CHARSET); Httpprotocolparams.setuseexpectcontinue (params, true);//time-out setting/* Timeout from Connection pool fetch */connmanagerparams.settimeout ( params, 1000);/* Connection Timeout */httpconnectionparams.setconnectiontimeout (params, 2000);/* Request timed out */ Httpconnectionparams.setsotimeout (params, 4000);//Set HttpClient support HTTP and HTTPS two modes schemeregistry Schreg = new Schemeregistry (); Schreg.register (New Scheme ("http", Plainsocketfactory.getsocketfactory (), +)); Schreg.register ( New Scheme ("https", Sslsocketfactory.getsocketfactory (), 443));//Use thread-safe connection management to create Httpclientclientconnectionmanager Conmgr = new Threadsafeclientconnmanager (params, schreg); mhttpclient = new Defaulthttpclient (conmgr, params);} return mhttpclient;}}

Method Getsavehttpclient () to obtain a thread-safe singleton httpclient, the comments are very detailed, nothing to say, can be used directly.

3, has been very perfect, still can optimize it?

You can use application to further refine the timing and other configurations for creating httpclient. Application Related knowledge: Links

New package name Org.yanzi.application, create a new Myapplication.java inside, 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.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;import android.app.Application; public class MyApplication 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 auto-generated method Stubsuper.onlowmemory (); This.shutdownhttpclient ();} /** Create HttpClient instance * @return */private HttpClient createhttpclient () {httpparams params = new Basichttpparams ();// Set basic parameters Httpprotocolparams.setversion (params, httpversion.http_1_1); Httpprotocolparams.setcontentcharset (params, CHARSET); Httpprotocolparams.setuseexpectcontinue (params, true);//time-out setting/* Timeout from Connection pool fetch */connmanagerparams.settimeout ( params, 1000);/* Connection Timeout */httpconnectionparams.setconnectiontimeout (params, 2000);/* Request timed out */ Httpconnectionparams.setsotimeout (params, 4000);//Set HttpClient support HTTP and HTTPS two modes schemeregistry Schreg = new Schemeregistry (); Schreg.register (New Scheme ("http", Plainsocketfactory.getsocketfactory (), +)); Schreg.register ( New Scheme ("https", Sslsocketfactory.getsocketfactory (), 443));//Use thread-safe connection management to create HTTPCLIentclientconnectionmanager conmgr = new Threadsafeclientconnmanager (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;}}

And then Androidmanifest.xml add:

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

    <application        android:name= "org.yanzi.application.MyApplication"        android:allowbackup= "true"        android:icon= "@drawable/ic_launcher"        android:label= "@string/app_name"        android:theme= "@style/apptheme" >        <activity            android:name= "org.yanzi.testtomecat.MainActivity"            android:label= "@string/app_ Name ">            <intent-filter>                <action android:name=" Android.intent.action.MAIN "/>                < Category android:name= "Android.intent.category.LAUNCHER"/>            </intent-filter>        </activity >    </application>

Then in activity, through mmyapplication = (MyApplication) getapplication ();

Mmyapplication.gethttpclient () can be used by httpclient.

You can see that the httpclient is instantiated in the OnCreate of application, and the connection manager is closed at low memory and shutdown, freeing up resources, which is better than writing to a normal 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.