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