我在我的Android应用程序中使用Loopj的AsyncHttpclient来发送异步请求以获取数据。如果服务器没有响应或者连接服务器需要10秒以上,我想取消该任务。我尝试设置超时,它在指定的持续时间后取消任务,而如果我没有设置任何超时,我会按预期得到响应。这是
public class HttpRestClient {
private final static String BASE_URL = "http://test.com/service.svc/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.setTimeout(2000);
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.setTimeout(2000);
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void postJSON(Context context, String url, HttpEntity entity, String contentType, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.setTimeout(2000);
client.post(context, getAbsoluteUrl(url), entity, contentType, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}