Android HttpClient线程安全

时间:2012-08-28 08:50:17

标签: android multithreading httpclient

我正在实现简单的HttpManager,它将用作单例,它可以并行执行来自不同线程的多个请求。你能看看那段代码并告诉我概念是否合适。

public class HttpManager implements IHttpManager {

    private static final String TAG = HttpManager.class.getSimpleName();    
    private static final String HOST
    private static final int PORT = 80;

    private Handler mHandler; 
    private HttpClient mHttpClient;

    private static HttpManager sInstance = new HttpManager();

    public static HttpManager instance() {
        return sInstance;
    }

    private HttpManager() {
        mHandler = new Handler();
        mHttpClient = new DefaultHttpClient();
    }

    @Override
    public void execute(final IHttpRequest request) {   
        final String action = request.getAction();
        final List<NameValuePair> params = translateParams(request.getParams());

        (new Thread() {
            public void run() {
                try {                   
                    URI uri =URIUtils.createURI("http",HOST+"/"+action+".php", 
                        PORT, "", URLEncodedUtils.format(params, "UTF-8"), null);                   
                    final HttpGet httpget = new HttpGet(uri);

                    try {
                        HttpResponse response = mHttpClient.execute(httpget);
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            InputStream instream = entity.getContent();
                            final String text = readStream(instream);
                            Log.d(TAG, text);
                            mHandler.post(new Runnable() {
                                public void run() {
                                    request.onCompleted(text);
                                }
                            });
                        }
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

2 个答案:

答案 0 :(得分:0)

我会改变它:

private static HttpManager sInstance = null;

public static HttpManager getInstance() {
    if( instance == null)
        sInstance = new HttpManager();

    return sInstance;
}

private HttpManager() {
    mHandler = new Handler();
    mHttpClient = new DefaultHttpClient();
}

答案 1 :(得分:0)

这样可行,但线程很昂贵,所以尽量避免创建它们。不要为每个请求创建一个请求,而是使用ThreadPoolExecutor。在execute方法中,不是创建Thread,而是创建Runnable并将其传递给Executor。

还要注意您使用的线程池大小。太多线程会让您的设备陷入困境。此外,过多的并发网络请求可能会导致性能下降,尤其是在移动网络上。