首先,asynctask是同步執行,AsyncHttpClient是同時執行。不要在客戶端內使用asynctask。像這樣只使用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);
}
給這樣的這種請求的URL從活動或片段
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.
}
});
問題是如何處理Asynctask和默認http客戶端的超時? –
@Prateek謝謝,它幫助。我現在使用AsyncHttpClient而沒有asynctask。在我重寫庫的所有onFailure方法後,它運行良好。 – StarWars
@StarWars很高興幫助。你可以接受這個答案,如果你想 – Prateek