如何取消在多线程DefaulHttpClient执行过程 [英] How to cancel DefaulHttpClient execution process in multithread

查看:200
本文介绍了如何取消在多线程DefaulHttpClient执行过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发依赖非常多的互联网,我检索经常使用此 RestClient类数据的Andr​​oid应用程序,该包装一些细节上采用DefaultHttpClient做网络的要求。

I am developing an android application that rely very much on internet, I retrieve data frequently using this RestClient Class, that wrap some detail on using DefaultHttpClient to do network request.

和我总是用不同的线程来执行HTTP请求,我创建一个类是这样的:

And I always use different thread to do the HTTP request, I create a class like this:

public class AsyncWorker {

    final String SERVER_URL = "http://api.blabla.com";
    RestClient client = new RestClient();

    public void requestHttp(final String url, final ArrayList<NameValuePair> params, final RequestListener listener) {
        new Thread(new Runnable() {

            public void run() {
                try {
                    client.setUrl(url);
                    client.setParams(params);
                    client.Execute(RestClient.RequestMethod.POST);
                    String response = client.getResponse();
                    listener.onComplete(response);
                } catch (Exception ex) {
                    Log.d("LOGIN", ex.getMessage());
                }
            }
        }).start();
    }
    etc...

所以,每当我需要做一个HTTP请求,我只需要创建 AsyncWorker 对象,并提供 RequestListener 回调接口。

So whenever I need to do a HTTP request, I only need to create AsyncWorker object, and provide the RequestListener callback interface.

但问题是,我怎么能取消HTTP请求时,PSS的返回/取消键,用户$ P $ ?在这种情况下,应用程序仍然是一个活动,比如我创建一个对话框,用户做从该对话框中的请求,然后后退按钮pressed,对话框解雇了,我需要在取消该请求那个时候。

But the problem is, how can I cancel the HTTP Request when the user press the back/cancel button? and in this case the application still is in one activity, for example I create a dialog, and the user do a request from that dialog, and then back button pressed, the dialog dismissed, and I need to cancel the request on that time.

推荐答案

我建议你看一看的 ClientConnectionManager 接口。这允许你做的东西一样释放连接,关闭连接等,您可能需要提高 RestClient 虽然实现 - 因为你的 RestClient 不公开的基本 DefaultHttpClient 对象(从中可以获取到 ClientConnectionManager 使用在 getClientConnectionManager()法)。

I suggest you take a look at the ClientConnectionManager interface. This allows you to do stuff like releasing a connection, shutting down a connection etc. You may need to enhance the implementation of RestClient though - since your RestClient does not expose the underlying DefaultHttpClient object (from which you can get to the ClientConnectionManager using the getClientConnectionManager() method).

这篇关于如何取消在多线程DefaulHttpClient执行过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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