位置: 编程技术 - 正文
推荐整理分享Android网络(4):HttpClient必经之路----使用线程安全的单例模式HttpClient,及HttpClient和Application的融合,希望有所帮助,仅作参考,欢迎阅读内容。
文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!
zz: class MyHttpClient {private static HttpClient mHttpClient = null;private static final String CHARSET = HTTP.UTF_8;//将构造函数封掉,只能通过对外接口来获取HttpClient实例private MyHttpClient(){}public static HttpClient getHttpClient(){if(mHttpClient == null){mHttpClient = new DefaultHttpClient();}return mHttpClient;}}
上面是最简单的一种单例,确实能够满足需要。但不能满足多线程的要求,即当同时完成多个Http请求时,就出马蛋了。
2、线程安全的HttpClient
幸运的是android已经提供了可以创建线程安全的HttpClient,即通过ClientConnectionManager 来完成。下面贴出完整代码:
[java] view plaincopyprint?<span style="font-family:Comic Sans MS;font-size:px;">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; //将构造函数封掉,只能通过对外接口来获取HttpClient实例 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(); //设置基本参数 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, CHARSET); HttpProtocolParams.setUseExpectContinue(params, true); //超时设置 /*从连接池中取连接的超时时间*/ ConnManagerParams.setTimeout(params, ); /*连接超时*/ HttpConnectionParams.setConnectionTimeout(params, ); /*请求超时*/ HttpConnectionParams.setSoTimeout(params, ); //设置HttpClient支持HTTp和HTTPS两种模式 SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), )); schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), )); //使用线程安全的连接管理来创建HttpClient ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg); mHttpClient = new DefaultHttpClient(conMgr, params); } return mHttpClient; } } </span> 方法getSaveHttpClient()即可获得线程安全的单例httpClient,注释很详细了啥都不说了,可以直接使用。3、已经很完美了,还能不能再优化呢?
可以使用Application来进一步优化创建HttpClient的时机及其他配置。Application的相关知识参见:链接
新建包名org.yanzi.application,在里面新建MyApplication.java,完整代码如下:
[java] view plaincopyprint?<span style="font-family:Comic Sans MS;font-size:px;">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; @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); mHttpClient = this.createHttpClient(); } @Override public void onTerminate() { // TODO Auto-generated method stub super.onTerminate(); this.shutdownHttpClient(); } @Override public void onLowMemory() { // TODO Auto-generated method stub super.onLowMemory(); this.shutdownHttpClient(); } /**创建HttpClient实例 * @return */ private HttpClient createHttpClient(){ HttpParams params = new BasicHttpParams(); //设置基本参数 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, CHARSET); HttpProtocolParams.setUseExpectContinue(params, true); //超时设置 /*从连接池中取连接的超时时间*/ ConnManagerParams.setTimeout(params, ); /*连接超时*/ HttpConnectionParams.setConnectionTimeout(params, ); /*请求超时*/ HttpConnectionParams.setSoTimeout(params, ); //设置HttpClient支持HTTp和HTTPS两种模式 SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), )); schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), )); //使用线程安全的连接管理来创建HttpClient ClientConnectionManager 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; } } </span> 然后再AndroidManifest.xml理添加:android:name="org.yanzi.application.MyApplication"
[html] view plaincopyprint?<span style="font-family:Comic Sans MS;font-size:px;"> <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></span> 然后再Activity里,通过mMyApplication = (MyApplication)getApplication();mMyApplication.getHttpClient()得到HttpClient就可以使用了。
可以看到在Application的onCreate里就实例化了HttpClient,且在低内存和关闭时关闭连接管理器,释放资源,比2中的写到一个普通文件里更优。
android网络相关的工具类 android网络相关的工具类uses-permissionandroid:name=android.permission.INTERNET/!--查询网络状态权限--uses-permissionandroid:name=android.permission.ACCESS_NETWORK_STATE/粘过去就可
Grade 编译 Android 解决 Error:more than one library with package name Grade编译Android解决Error:morethanonelibrarywithpackagenameError:morethanonelibrarywithpackagename'com.app.XX'Youcantemporarilydisablethiserrorwithandroid.enforceUniquePackageName=falseHowever,thi
一种夜间模式简单实现方案 在android应用开发时,可能会用到夜间模式,一般的解决方案就是用主题。夜间模式一般就涉及道背景,亮度,字体颜色等,所以可以简单通过自定义组
标签: Android网络(4):HttpClient必经之路----使用线程安全的单例模式HttpClient,及HttpClient和Application的融合
本文链接地址:https://www.jiuchutong.com/biancheng/383307.html 转载请保留说明!友情链接: 武汉网站建设