取消同步多部件请求



我需要使用loopj从AsyncTask发送多部分post请求,所以我被迫使用SyncHttpClient。

阅读源代码注释,我了解到从同步请求的post方法返回的请求句柄不能用于取消请求,因为它在返回时已经完成(这是有意义的)。不过看起来像进退两难。

是否有其他方法可以取消当前正在运行的同步请求?是否可以使用SyncHttpClient.cancelAllRequests(true);从UI线程?那么,来自UI线程的SyncHttpClient.cancelAllRequests(true)不起作用。是bug吗?

只要确保你可以使用AsyncHttpRequest,如果你想要能够取消运行的请求。如果你从另一个线程甚至是AsyncTask运行异步http请求并不重要,你只需要确保在主线程上调用AsyncHttpRequest。您可以通过使用

将其强制到主线程中来轻松地做到这一点。
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
  public void run() {
// run your AsyncHttpRequest in here. 
// Since it is called from the main thread it will run asynchronously
// and therefore it can be cancelled easily by calling client.cancelAllRequests(true) 
  }
};
mainHandler.post(myRunnable);

最新更新