0

我正在实现简单的 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();
    }
}
4

2 回答 2

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();
}
于 2012-08-28T08:58:12.833 回答
0

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

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

于 2012-08-30T18:26:10.577 回答