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

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

问题描述

我用的AsyncTask 来initalize AndroidHttpClient 并执行 doInBackground POST请求()。我希望用户能够消除由pressing后退按钮请求。 的AsyncTask 有一个取消()方法,它不仅改变了 isCancelled的布尔返回值() ,然后等待 doInBackground()调用之前完成<$​​ C $ C> onCancelled()。这意味着的AsyncTask 离开到 doInBackground()方法来连续检查任务是否已被取消(使用 isCancelled())。如果已被取消, doInBackground()应该返回prematurely prematurely。我遇到的问题是,99%的工作线程在 doInBackground()执行停止的:

 的Htt presponse响应= httpClient.execute(请求[0]);
 

,因为该同步函数调用封装了请求的网络方面。我怎样才能通过取消请求中途?

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

我也在考虑覆盖的AsyncTask 取消()的方法,它可以更好地工作。

有什么建议?

解决方案

  httpclient.getConnectionManager()关闭();
 

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.

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

Any suggestions?

解决方案

httpclient.getConnectionManager().shutdown();

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

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