如何取消 Android http 请求? [英] How do I cancel an Android http request?

查看:65
本文介绍了如何取消 Android http 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AsyncTask 初始化 AndroidHttpClient 并在 doInBackground() 中执行 POST 请求.我希望用户能够通过按后退按钮来取消请求.AsyncTask 有一个 cancel() 方法,它只改变 isCancelled() 的布尔返回值,然后等待 doInBackground() 在调用 onCancelled() 之前完成.这意味着 AsyncTask 将它留给 doInBackground() 方法来持续检查任务是否已被取消(使用 isCancelled()).如果它已被取消,doInBackground() 应该提前返回.我遇到的问题是 doInBackground() 中 99% 的工作线程的执行停止于:

I'm using AsyncTask to initalize AndroidHttpClient and execute a POST request in doInBackground(). I'd like the user to be able to cancel the request by pressing the back button. AsyncTask has a cancel() method which only changes the boolean return value of isCancelled() and then waits for doInBackground() to finish before calling onCancelled(). This means that AsyncTask leaves it up to the doInBackground() method to continuously check whether the task has been cancelled (using isCancelled()). If it has been cancelled, doInBackground() should return prematurely prematurely. The problem I'm having is that 99% the execution of the worker thread in doInBackground() stops on:

HttpResponse response = httpClient.execute(request[0]);

因为这个同步函数调用封装了请求的网络方面.如何中途取消请求?

because this synchronous function call encapsulates the network aspects of the request. How can I cancel the request midway through?

我正在考虑尝试在请求期间更改超时时间,但这似乎是线程不安全的.

I'm considering trying to change the timeout time during the request, but this seems thread unsafe.

我也在考虑覆盖 AsyncTaskcancel() 方法,这可能会更好.

I'm also considering overriding AsyncTask's cancel() method, which may work better.

有什么建议吗?

推荐答案

httpclient.getConnectionManager().shutdown();

这篇关于如何取消 Android http 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆