---
title: "HttpClient 多线程"
author: "ipFire"
date: "2011-04-03T09:39:56Z"
tags: []
categories: ["移动开发"]
slug: "httpclient"
draft: false
lastmod: "2011-04-03T09:39:56Z"
id: 985604
url: "https://ipfire.iteye.com/blog/985604"
---

关于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

```
<application android:icon="@drawable/icon" android:label="@string/app_name" android:name= ".ApplicationHc">
```