Android HttpClient多线程

关于HttpClient的使用:

1、如果应用程序需要执行多个HTTP调用,则应该创建一个为所有HTTP请求服务的HttpClient,可以将HttpClient关联到Android的应用程序对象中

2、HttpClient同时发出多个请求可能引起的多线程问题,可以使用ThreadSafeClientConnManager创建DefaultHttpClient

主要代码:

public class ApplicationHc extends Application {

	private static final String TAG = "ApplicationHc";
	private HttpClient httpClient;

	@Override
	public void onCreate() {
		super.onCreate();
		httpClient = createHttpClient();
	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
		shutdownHttpClient();
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
		shutdownHttpClient();
	}

	// 创建HttpClient对象
	private HttpClient createHttpClient() {
		Log.i(TAG, "Create HttpClient...");

		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params,
				HTTP.DEFAULT_CONTENT_CHARSET);
		HttpProtocolParams.setUseExpectContinue(params, true);

		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schReg.register(new Scheme("https",
				SSLSocketFactory.getSocketFactory(), 443));

		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
				params, schReg);

		return new DefaultHttpClient(conMgr, params);
	}

	// 关闭HttpClent
	private void shutdownHttpClient() {
		if (httpClient != null && httpClient.getConnectionManager() != null) {
			httpClient.getConnectionManager().shutdown();
		}
	}

	public HttpClient getHttpClient() {
		return httpClient;
	}
}

在Activity中使用:

private String getHttpContent(){
    String con = null;
    try{
        ApplicationHc  app= (ApplicationHc)this.getApplication();
        HttpClient client = app.getHttpClient();
        HttpGet get = new HttpGet();
        get.setURI(new URI("http://www.google.com/ig/api?weather=Guangzhou"));
        HttpResponse response = client.execute(get);
        
        con = EntityUtils.toString(response.getEntity());
    }catch (Exception e) {
        e.printStackTrace();
    }
    return con;
}

修改AndroidManifest.xml

暂无评论
  • 1:请一针见血的评论。
  • 2:评论需要审核通过后才能显示。
  • 3:评论字数限制在1000字以内。
  • 当前字数:0
热门文章
推荐文章
随机文章
关于本站 - 广告服务 - 版权声明 - 联系我们 - 友情链接 - 网站地图 - 帮助中心