HttpClient ConnectionPoolTimeoutException: Timeout waiting for connection

33968 단어
최근에 응용 프로그램 중의 한 코드를 최적화하여 이전에 단선정 직렬로 실행되었던 일련의 http 요청을 다선정 병렬 실행으로 바꾸어 효율을 높였다.그 결과 프로그램이 처음 실행되었을 때 비교적 정상적이었는데 뒤에 http 요청이 많아진 후에 이상을 던졌다. 이상 창고 정보는 다음과 같다.
01-07 11:45:45.576: W/System.err(4727): org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection
01-07 11:45:45.586: W/System.err(4727): 	at org.apache.http.impl.conn.tsccm.ConnPoolByRoute.getEntryBlocking(ConnPoolByRoute.java:353)
01-07 11:45:45.586: W/System.err(4727): 	at org.apache.http.impl.conn.tsccm.ConnPoolByRoute$1.getPoolEntry(ConnPoolByRoute.java:238)
01-07 11:45:45.586: W/System.err(4727): 	at org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager$1.getConnection(ThreadSafeClientConnManager.java:176)
01-07 11:45:45.586: W/System.err(4727): 	at org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection
01-07 11:45:45.586: W/System.err(4727): 	at org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection
01-07 11:45:45.586: W/System.err(4727): org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection
01-07 11:45:45.586: W/System.err(4727): 	at org.apache.http.impl.conn.tsccm.ConnPoolByRoute.getEntryBlocking(ConnPoolByRoute.java:353)
01-07 11:45:45.586: W/System.err(4727): 	at org.apache.http.impl.conn.tsccm.ConnPoolByRoute$1.getPoolEntry(ConnPoolByRoute.java:238)
01-07 11:45:45.596: W/System.err(4727): 	at org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager$1.getConnection(ThreadSafeClientConnManager.java:176)
01-07 11:45:45.596: W/System.err(4727): 	at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:326)
01-07 11:45:45.596: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-07 11:45:45.596: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-07 11:45:45.596: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-07 11:45:45.596: W/System.err(4727): 	at com.yulore.yellowpage.http.NetUtil.post(NetUtil.java:92)
01-07 11:45:45.596: W/System.err(4727): 	at com.yulore.yellowpage.business.ResolveTask.recognize(ResolveTask.java:123)
01-07 11:45:45.596: W/System.err(4727): 	at com.yulore.yellowpage.business.ResolveTask.call(ResolveTask.java:43)
01-07 11:45:45.596: W/System.err(4727): 	at com.yulore.yellowpage.business.ResolveTask.call(ResolveTask.java:1)
01-07 11:45:45.606: W/System.err(4727): 	at org.apache.http.impl.conn.tsccm.ConnPoolByRoute.getEntryBlocking(ConnPoolByRoute.java:353)
01-07 11:45:45.606: W/System.err(4727): 	at org.apache.http.impl.conn.tsccm.ConnPoolByRoute$1.getPoolEntry(ConnPoolByRoute.java:238)
01-07 11:45:45.606: W/System.err(4727): 	at org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager$1.getConnection(ThreadSafeClientConnManager.java:176)
01-07 11:45:45.606: W/System.err(4727): 	at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:326)
01-07 11:45:45.606: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-07 11:45:45.606: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-07 11:45:45.606: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-07 11:45:45.606: W/System.err(4727): 	at com.yulore.yellowpage.http.NetUtil.post(NetUtil.java:92)
01-07 11:45:45.606: W/System.err(4727): 	at com.yulore.yellowpage.business.ResolveTask.recognize(ResolveTask.java:123)
01-07 11:45:45.606: W/System.err(4727): 	at com.yulore.yellowpage.business.ResolveTask.call(ResolveTask.java:43)
01-07 11:45:45.606: W/System.err(4727): 	at com.yulore.yellowpage.business.ResolveTask.call(ResolveTask.java:1)
01-07 11:45:45.606: W/System.err(4727): 	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-07 11:45:45.616: W/System.err(4727): 	at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-07 11:45:45.616: W/System.err(4727): org.apache.http.impl.conn.tsccm.ConnPoolByRoute.getEntryBlocking(ConnPoolByRoute.java:353)
01-07 11:45:45.616: W/System.err(4727): 	at org.apache.http.impl.conn.tsccm.ConnPoolByRoute$1.getPoolEntry(ConnPoolByRoute.java:238)
01-07 11:45:45.616: W/System.err(4727): 	at org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager$1.getConnection(ThreadSafeClientConnManager.java:176)
01-07 11:45:45.616: W/System.err(4727): 	at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:326)
01-07 11:45:45.616: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-07 11:45:45.616: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-07 11:45:45.616: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-07 11:45:45.616: W/System.err(4727): 	at com.yulore.yellowpage.http.NetUtil.post(NetUtil.java:92)
01-07 11:45:45.616: W/System.err(4727): 	at com.yulore.yellowpage.business.ResolveTask.recognize(ResolveTask.java:123)
01-07 11:45:45.616: W/System.err(4727): 	at com.yulore.yellowpage.business.ResolveTask.call(ResolveTask.java:43)
01-07 11:45:45.616: W/System.err(4727): 	at com.yulore.yellowpage.business.ResolveTask.call(ResolveTask.java:1)
01-07 11:45:45.616: W/System.err(4727): 	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-07 11:45:45.616: W/System.err(4727): 	at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-07 11:45:45.616: W/System.err(4727): 	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
01-07 11:45:45.616: W/System.err(4727): 	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-07 11:45:45.616: W/System.err(4727): 	at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-07 11:45:45.626: W/System.err(4727): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-07 11:45:45.626: W/System.err(4727): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-07 11:45:45.626: W/System.err(4727): 	at java.lang.Thread.run(Thread.java:856)
01-07 11:45:45.626: W/System.err(4727): org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:326)
01-07 11:45:45.626: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-07 11:45:45.636: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-07 11:45:45.636: W/System.err(4727): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-07 11:45:45.636: W/System.err(4727): 	at com.yulore.yellowpage.http.NetUtil.post(NetUtil.java:92)
01-07 11:45:45.636: W/System.err(4727): 	at com.yulore.yellowpage.business.ResolveTask.recognize(ResolveTask.java:123)
01-07 11:45:45.636: W/System.err(4727): 	at 	at 	at com.yulore.yellowpage.business.ResolveTask.call(ResolveTask.java:43)
01-07 11:45:45.636: W/System.err(4727): 	at com.yulore.yellowpage.business.ResolveTask.call(ResolveTask.java:1)
01-07 11:45:45.636: W/System.err(4727): 	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.FutureTask.run(FutureTask.java:137)java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-07 11:45:45.646: W/System.err(4727): 	at java.lang.Thread.run(Thread.java:856)
01-07 11:45:45.646: W/System.err(4727): java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-07 11:45:45.646: W/System.err(4727): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-07 11:45:45.646: W/System.err(4727): 	at java.lang.Thread.run(Thread.java:856)
01-07 11:45:45.656: W/System.err(4727): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-07 11:45:45.656: W/System.err(4727): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-07 11:45:45.656: W/System.err(4727): 	at java.lang.Thread.run(Thread.java:856)

org.apache.http.conn.ConnectionPool Timeout Exception: Timeout waiting for connection, 영어를 잘하는 사람은 한눈에 알아볼 수 있습니다. ConnectionPool 요청이 시간을 초과했습니다. 왜 이런 오류가 발생했습니까?
원인: http 연결 탱크의 연결 개수는 일정합니다. http 요청을 실행할 때마다 연결이 풀리지 않으면 http 연결 탱크의 수가 점점 적어지고 마지막에 http 연결을 사용할 수 없습니다.
해결 방법: 요청이 성공하거나 실패할 때마다 연결 자원을 수동으로 방출합니다.
오류 코드를 다음과 같이 붙여 넣습니다.
package com.yulore.yellowpage.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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.message.BasicNameValuePair;
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 org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.yulore.yellowpage.util.LogUtil;

/**
 * 
 * @author Mathew
 * 
 */
public class NetUtil {
	private static HttpClient customerHttpClient;
	private static final String CHARSET_UTF8 = HTTP.UTF_8;
	private static final String TAG = NetUtil.class.getSimpleName();

	/**
	 * post   
	 * 
	 * @param vo
	 * @return
	 * @throws JSONException
	 */
	public static Object post(RequestVo vo) throws JSONException,
			ClientProtocolException, SocketTimeoutException, IOException {
		HttpClient client = getNewHttpClient(vo.context);
		LogUtil.e(TAG, "post URL:" + vo.requestUrl);
		
		HttpPost post = new HttpPost(vo.requestUrl);
		HttpParams params = new BasicHttpParams();//
		if(vo.timeout!=0){
			HttpConnectionParams.setConnectionTimeout(params, vo.timeout); //     
			HttpConnectionParams.setSoTimeout(params, vo.timeout); //     
		}

		post.setParams(params);
		post.setHeader("Accept-Encoding", "gzip");

		Object obj = null;

		if (vo.requestDataMap != null) {
			HashMap<String, String> map = vo.requestDataMap;
			ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
			for (Map.Entry<String, String> entry : map.entrySet()) {
				BasicNameValuePair pair = new BasicNameValuePair(
						entry.getKey(), entry.getValue());
				pairList.add(pair);
			}
			HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
			post.setEntity(entity);
		}
		HttpResponse response = client.execute(post);//              ==
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			
			InputStream in = response.getEntity().getContent();
			Header contentEncoding = response.getFirstHeader("Content-Encoding");
			if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
				LogUtil.e(TAG, "gzip InputStream in post");
				in = new GZIPInputStream(in);
			}
			String result = getHTMLContent(in);
//			String result = EntityUtils.toString(response.getEntity(), "UTF-8");
			
			LogUtil.w(TAG, result);//      JSON   
			if (vo.callback != null) {
				JSONObject json = new JSONObject(result);
				String status = json.getString("status");
				if ("0".equals(status)) {
					LogUtil.i(TAG, "  Json ");
					vo.callback.process(result);
				}
			}
			
			obj = vo.jsonParser.parseJSON(result);//            

			return obj;
		}

		return null;
	}

	/**
	 * 
	 * @param vo
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws SocketTimeoutException
	 */
	public static Object get(RequestVo vo) throws JSONException,
			ClientProtocolException, IOException,SocketTimeoutException {
		HttpClient client = getNewHttpClient(vo.context);

		LogUtil.e(TAG, "get URL:" + vo.requestUrl);
		//            

		HttpGet get = new HttpGet(vo.requestUrl);

		HttpParams params = new BasicHttpParams();//
		if(vo.timeout!=0){
			HttpConnectionParams.setConnectionTimeout(params, vo.timeout); //     
			HttpConnectionParams.setSoTimeout(params, vo.timeout); //     
		}
		get.setParams(params);
		get.setHeader("Accept-Encoding", "gzip");
		
		Object obj = null;

		HttpResponse response = client.execute(get);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

			InputStream in = response.getEntity().getContent();
			Header contentEncoding = response.getFirstHeader("Content-Encoding");
			if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
				LogUtil.e(TAG, "gzip InputStream in get");
				in = new GZIPInputStream(in);
			}
			String result = getHTMLContent(in);
//			String result = EntityUtils.toString(response.getEntity(), "UTF-8");

			LogUtil.w(TAG, result);//      JSON   
			if (vo.callback != null) {
				JSONObject json = new JSONObject(result);
				String status = json.getString("status");
				if ("0".equals(status)) {
					LogUtil.i(TAG, "  Json ");
					vo.callback.process(result);
				}
			}
			obj = vo.jsonParser.parseJSON(result);
		}

		return obj;
	}
	
	private static String getHTMLContent(InputStream in) {  
        StringBuffer sb = new StringBuffer();  
        BufferedReader br = null;
        try {  
        	br = new BufferedReader(new InputStreamReader(in,"utf-8"));
            String line = null;  
            while((line=br.readLine())!=null){  
                sb.append(line);  
            }  
              
        } catch (IOException e) {  
            e.printStackTrace();  
        }finally{  
            try {  
                if(br!=null)
                	br.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
          
        return sb.toString();  
    }  
	
	/**
	 * 
	 * @param vo
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws SocketTimeoutException
	 */
	public static String requestGet(Context context,String url) throws JSONException,
			ClientProtocolException, IOException,SocketTimeoutException {
		
		HttpClient client = getNewHttpClient(context);

		LogUtil.e(TAG, "requestGet URL:" + url);
		//            

		HttpGet get = new HttpGet(url);

		HttpParams params = new BasicHttpParams();//
		
		get.setParams(params);
		get.setHeader("Accept-Encoding", "gzip");
		
		String result = null;

		HttpResponse response = client.execute(get);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

			InputStream in = response.getEntity().getContent();
			Header contentEncoding = response.getFirstHeader("Content-Encoding");
			if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
				LogUtil.e(TAG, "gzip InputStream in requestGet");
				in = new GZIPInputStream(in);
			}
			result = getHTMLContent(in);

			LogUtil.w(TAG, result);//      JSON   
		}

		return result;
	}

	public interface ResponseStrCallback {
		public void process(String responseStr);
	}

	private static synchronized HttpClient getNewHttpClient(Context context) {
		if (null == customerHttpClient) {
			HttpParams params = new BasicHttpParams();
			//         
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET_UTF8);
			// HttpProtocolParams.setUseExpectContinue(params, true);
			HttpProtocolParams
					.setUserAgent(
							params,
							"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
									+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
			//     
			/*               */
			ConnManagerParams.setTimeout(params, 8000);
			/*      */
			int ConnectionTimeOut = 10000;
			if (!isWifiDataEnable(context)) {
				ConnectionTimeOut = 15000;
			}
			HttpConnectionParams
					.setConnectionTimeout(params, ConnectionTimeOut);
			/*      */
			HttpConnectionParams.setSoTimeout(params, ConnectionTimeOut);
			
			//      HttpClient  HTTP HTTPS    
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory
					.getSocketFactory(), 443));

			//               HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);
			customerHttpClient = new DefaultHttpClient(conMgr, params);
		}
		return customerHttpClient;
	}

	/**
	 *   wifi     
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static boolean isWifiDataEnable(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean isWifiDataEnable = false;
		isWifiDataEnable = connectivityManager.getNetworkInfo(
				ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
		return isWifiDataEnable;
	}

	/**
	 *           
	 * 
	 * @param context
	 * @return
	 */
	public static boolean hasNetwork(Context context) {
		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo workinfo = con.getActiveNetworkInfo();
		if (workinfo == null || !workinfo.isAvailable()) {
			// Toast.makeText(context, R.string.network_not_available,
			// Toast.LENGTH_SHORT)
			// .show();
			return false;
		}
		return true;
	}
}

나는 두 곳을 바꾸었다.
(1) getNewHttpClient 메서드는 다음 코드를 추가합니다.
//                    
			ConnManagerParams.setTimeout(params, 20000);
			//          
	        ConnManagerParams.setMaxTotalConnections(params, 200);  
	        //              
	        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);  
	        ConnManagerParams.setMaxConnectionsPerRoute(params,connPerRoute);  

(2) get/post 방법에서 InputStream을 처리한 후 InputStream을 닫습니다
public static Object get(RequestVo vo) throws JSONException,
			ClientProtocolException, IOException,SocketTimeoutException {
		HttpClient client = getNewHttpClient(vo.context);

		LogUtil.e(TAG, "get URL:" + vo.requestUrl);
		//            

		HttpGet get = new HttpGet(vo.requestUrl);

		HttpParams params = new BasicHttpParams();//
		if(vo.timeout!=0){
			HttpConnectionParams.setConnectionTimeout(params, vo.timeout); //     
			HttpConnectionParams.setSoTimeout(params, vo.timeout); //     
		}
		get.setParams(params);
		get.setHeader("Accept-Encoding", "gzip");
		
		Object obj = null;

		HttpResponse response = client.execute(get);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			InputStream in = null;
			try{
				in = response.getEntity().getContent();
				Header contentEncoding = response.getFirstHeader("Content-Encoding");
				if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					LogUtil.e(TAG, "gzip InputStream in get");
					in = new GZIPInputStream(in);
				}
				String result = getHTMLContent(in);
//				String result = EntityUtils.toString(response.getEntity(), "UTF-8");

				LogUtil.d(TAG, result);//      JSON   
				
				if (vo.callback != null) {
					JSONObject json = new JSONObject(result);
					String status = json.getString("status");
					if ("0".equals(status)) {
						LogUtil.i(TAG, "  Json ");
						vo.callback.process(result);
					}
				}
				obj = vo.jsonParser.parseJSON(result);
			}finally{
				if(in!=null){
					try {
						in.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		return obj;
	}

인.close ()는finally에 두면 매번 InputStream을 닫습니다.
마지막으로 전체 코드를 붙여 넣습니다.
package com.yulore.yellowpage.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
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.message.BasicNameValuePair;
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 org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.yulore.yellowpage.util.LogUtil;

/**
 *   http      
 */
public class NetUtil {
	private static HttpClient customerHttpClient;
	private static final String CHARSET_UTF8 = HTTP.UTF_8;
	private static final String TAG = NetUtil.class.getSimpleName();

	/**
	 * post   
	 * 
	 * @param vo
	 * @return
	 * @throws JSONException
	 */
	public static Object post(RequestVo vo) throws JSONException,
			ClientProtocolException, SocketTimeoutException, ConnectTimeoutException,IOException {
		HttpClient client = getNewHttpClient(vo.context);
		LogUtil.e(TAG, "post URL:" + vo.requestUrl);
		
		HttpPost post = new HttpPost(vo.requestUrl);
		HttpParams params = new BasicHttpParams();//
		if(vo.timeout!=0){
			HttpConnectionParams.setConnectionTimeout(params, vo.timeout); //     
			HttpConnectionParams.setSoTimeout(params, vo.timeout); //     
		}

		post.setParams(params);
		post.setHeader("Accept-Encoding", "gzip");
		
		if (vo.requestDataMap != null) {
			HashMap<String, String> map = vo.requestDataMap;
			ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
			for (Map.Entry<String, String> entry : map.entrySet()) {
				BasicNameValuePair pair = new BasicNameValuePair(
						entry.getKey(), entry.getValue());
				pairList.add(pair);
			}
			HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
			post.setEntity(entity);
		}
		HttpResponse response = client.execute(post);//              ==
		
		Object obj = null;
		
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			InputStream in = null;
			try{
				in = response.getEntity().getContent();
				Header contentEncoding = response.getFirstHeader("Content-Encoding");
				if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					LogUtil.e(TAG, "gzip InputStream in post");
					in = new GZIPInputStream(in);
				}
				String result = getHTMLContent(in);
//				String result = EntityUtils.toString(response.getEntity(), "UTF-8");
				
				LogUtil.d(TAG, result);//      JSON   
				
				if (vo.callback != null) {
					JSONObject json = new JSONObject(result);
					String status = json.getString("status");
					if ("0".equals(status)) {
						LogUtil.i(TAG, "  Json ");
						vo.callback.process(result);
					}
				}
				obj = vo.jsonParser.parseJSON(result);//            
			}finally{
				if(in!=null){
					try {
						in.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		return obj;
	}

	/**
	 * 
	 * @param vo
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws SocketTimeoutException
	 */
	public static Object get(RequestVo vo) throws JSONException,
			ClientProtocolException, IOException,SocketTimeoutException {
		HttpClient client = getNewHttpClient(vo.context);

		LogUtil.e(TAG, "get URL:" + vo.requestUrl);
		//            

		HttpGet get = new HttpGet(vo.requestUrl);

		HttpParams params = new BasicHttpParams();//
		if(vo.timeout!=0){
			HttpConnectionParams.setConnectionTimeout(params, vo.timeout); //     
			HttpConnectionParams.setSoTimeout(params, vo.timeout); //     
		}
		get.setParams(params);
		get.setHeader("Accept-Encoding", "gzip");
		
		Object obj = null;

		HttpResponse response = client.execute(get);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			InputStream in = null;
			try{
				in = response.getEntity().getContent();
				Header contentEncoding = response.getFirstHeader("Content-Encoding");
				if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					LogUtil.e(TAG, "gzip InputStream in get");
					in = new GZIPInputStream(in);
				}
				String result = getHTMLContent(in);
//				String result = EntityUtils.toString(response.getEntity(), "UTF-8");

				LogUtil.d(TAG, result);//      JSON   
				
				if (vo.callback != null) {
					JSONObject json = new JSONObject(result);
					String status = json.getString("status");
					if ("0".equals(status)) {
						LogUtil.i(TAG, "  Json ");
						vo.callback.process(result);
					}
				}
				obj = vo.jsonParser.parseJSON(result);
			}finally{
				if(in!=null){
					try {
						in.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		return obj;
	}
	
	private static String getHTMLContent(InputStream in) {  
        StringBuffer sb = new StringBuffer();  
        BufferedReader br = null;
        try {  
        	br = new BufferedReader(new InputStreamReader(in,"utf-8"));
            String line = null;  
            while((line=br.readLine())!=null){  
                sb.append(line);  
            }  
              
        } catch (IOException e) {  
            e.printStackTrace();  
        }finally{  
            try {  
                if(br!=null)
                	br.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
          
        return sb.toString();  
    }  
	
	/**
	 * 
	 * @param vo
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws SocketTimeoutException
	 */
	public static String requestGet(Context context,String url) throws JSONException,
			ClientProtocolException, IOException,SocketTimeoutException {
		
		HttpClient client = getNewHttpClient(context);

		LogUtil.e(TAG, "requestGet URL:" + url);
		//            

		HttpGet get = new HttpGet(url);

		HttpParams params = new BasicHttpParams();//
		
		get.setParams(params);
		get.setHeader("Accept-Encoding", "gzip");
		
		String result = null;

		HttpResponse response = client.execute(get);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			InputStream in = null;
			try{
				in = response.getEntity().getContent();
				Header contentEncoding = response.getFirstHeader("Content-Encoding");
				if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					LogUtil.e(TAG, "gzip InputStream in requestGet");
					in = new GZIPInputStream(in);
				}
				result = getHTMLContent(in);

				LogUtil.d(TAG, result);//      JSON   
			}finally{
				if(in!=null){
					try {
						in.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		return result;
	}

	public interface ResponseStrCallback {
		public void process(String responseStr);
	}

	private static synchronized HttpClient getNewHttpClient(Context context) {
		if (null == customerHttpClient) {
			HttpParams params = new BasicHttpParams();
			//         
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET_UTF8);
			// HttpProtocolParams.setUseExpectContinue(params, true);
			HttpProtocolParams
					.setUserAgent(
							params,
							"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
									+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
			//                    
			ConnManagerParams.setTimeout(params, 20000);
			//          
	        ConnManagerParams.setMaxTotalConnections(params, 200);  
	        //              
	        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);  
	        ConnManagerParams.setMaxConnectionsPerRoute(params,connPerRoute);  
	        
	        /*      */
			int ConnectionTimeOut = 10000;
			if (!isWifiDataEnable(context)) {
				ConnectionTimeOut = 15000;
			}
			HttpConnectionParams
					.setConnectionTimeout(params, ConnectionTimeOut);
			/*      */
			HttpConnectionParams.setSoTimeout(params, ConnectionTimeOut);
			
			//      HttpClient  HTTP HTTPS    
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory
					.getSocketFactory(), 443));

			//               HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);
			customerHttpClient = new DefaultHttpClient(conMgr, params);
		}
		return customerHttpClient;
	}

	/**
	 *   wifi     
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static boolean isWifiDataEnable(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean isWifiDataEnable = false;
		isWifiDataEnable = connectivityManager.getNetworkInfo(
				ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
		return isWifiDataEnable;
	}

	/**
	 *           
	 * 
	 * @param context
	 * @return
	 */
	public static boolean hasNetwork(Context context) {
		if(context==null){
			LogUtil.e(TAG, "context is null");
			return false;
		}
		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo workinfo = con.getActiveNetworkInfo();
		if (workinfo == null || !workinfo.isAvailable()) {
			// Toast.makeText(context, R.string.network_not_available,
			// Toast.LENGTH_SHORT)
			// .show();
			return false;
		}
		return true;
	}
}

HttpClient 사용에 관해서는 HttpClient 홈페이지에서 볼 수 있습니다. HttpClient 3.x 및 HttpClient 4.x의 사용은 여전히 약간의 차이가 있다
HttpClient 홈페이지:http://hc.apache.org/
HttpClient 4.3 Tutorial:http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/index.html

좋은 웹페이지 즐겨찾기