简体   繁体   English

如何取消从AsyncTask调用的HTTP GET请求?

[英]How can I cancel an HTTP GET request called from an AsyncTask?

I am using a static web services class to call an HTTP GET request and want to be able to cancel the request/AsyncTask when the user presses the back button. 我正在使用静态Web服务类来调用HTTP GET请求,并希望能够在用户按下后退按钮时取消请求/ AsyncTask。

I check isCancelled() periodically in doInBackground, which works for all other operations, but if the HTTP request is taking place when the user hits back then the task won't be canceled until the result is received or it times out. 我在doInBackground中定期检查isCancelled(),它适用于所有其他操作,但如果在用户回击时发生HTTP请求,则在收到结果或超时之前,任务不会被取消。

Because of the static call to WebServices.getDeviceId() I do not have a handle on the HTTP client, so I can't use httpclient.getConnectionManager().shutdown(); 由于对WebServices.getDeviceId()的静态调用,我在HTTP客户端上没有句柄,所以我不能使用httpclient.getConnectionManager()。shutdown(); to stop the connection. 停止连接 Anybody have any ideas on how I can solve this issue? 有人对我如何解决这个问题有任何想法?

@Override
    protected Void doInBackground(Void... params) {
        if((mInstance.getDeviceId() == null) && !isCancelled()) {
            String deviceId = WebServices.getDeviceId();
        }

        return null;
    }

If you want to interrupt the http request, you need a reference to it and call yourHttpRequest.abort() 如果要中断http请求,则需要对其进行引用并调用yourHttpRequest.abort()

In WebServices class, can't you add a method like abortHttpRequest() and add a reference to the current HttpRequest? 在WebServices类中,你不能添加像abortHttpRequest()这样的方法并添加对当前HttpRequest的引用吗?

You may need to manage a queue of http requests and abort the correct one. 您可能需要管理http请求队列并中止正确的请求。

This is from SDK: 这是来自SDK:

 Cancelling a task

A task can be cancelled at any time by invoking cancel(boolean). 
Invoking this method will cause subsequent calls to isCancelled() 
to return true. 
After invoking this method, onCancelled(Object), instead of 
onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. 
To ensure that a task is cancelled as quickly as possible, 
you should always check the return value of isCancelled() periodically from 
doInBackground(Object[]), if possible (inside a loop for instance.)

and then 接着

if (isCancelled()) 
     break;
else
{
   // do your work here
}

this is the answer on so 就是答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM