首先 asynctask 是同步执行,AsyncHttpClient 是同时执行。不要在异步任务中使用客户端。像这样只使用 AsyncHttpclient。创建通用请求处理程序和侦听器。您还可以为所需的每个请求创建不同的请求方法,例如 makeRequest,还可以创建不同的侦听器。
public class RequestHandler{
private static RequestHandler instance;
private AsyncHttpClient client;
private RequestHandler(){
client = new AsyncHttpClient();
}
public static RequestHandler getInstance(){
if(instance == null){
instance = new RequestHandler();
}
return instance;
}
// You can add more parameters if you need here.
public void makeRequest(String url, RequestListener listener){
client.get(url, new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// called before request is started
//Some debugging code here
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
listener.onSuccess(statusCode, headers, response);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable exception) {
listener.onFailure(statusCode, headers, errorResponse,exception);
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
//Some debugging code here, show retry dialog, feedback etc.
}
@Override
public void onRetry(int retryNo) {
//Some debugging code here-------
}
});
}
}
public interface RequestListener{
public void onSuccess(int statusCode, Header[] headers, byte[] response);
public void onFailure(int statusCode, Header[] headers, byte errorResponse, Throwable e);
}
从活动或片段中提供这样的请求网址
RequestHandler handler = RequestHandler.getInstance();
handler.makeRequest("http://www.google.com", new RequestListener(){
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// do whatever you want here.
}
});