【问题标题】:Cancel/abort a connection from the ThreadSafeClientConnManager connection pool从 ThreadSafeClientConnManager 连接池取消/中止连接
【发布时间】:2009-10-14 10:03:43
【问题描述】:

我正在使用ThreadSafeClientConnManager 来管理一个客户端连接池,因为我的应用程序有多个线程,它们同时连接到一个网络服务器。

抽象示例代码:

HttpClient httpClient;
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(parameters,schReg);
httpclient = new DefaultHttpClient(conMgr, parameters);

现在让我们说这个线程正在下载一个大文件,但是我的应用程序的用户正在切换到另一个活动/屏幕。因此该文件是不必要的,我想中止这个下载连接。

ThreadSafeClientConnManager我找到了这个方法:

public ClientConnectionRequest requestConnection (HttpRoute route, Object state) 返回一个新的 ClientConnectionRequest,从中可以获取一个 ManagedClientConnection 或者请求可以中止

到目前为止我一直在使用:

HttpGet httpRequest = new HttpGet(URL_TO_FILE);
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
[...]

现在据我了解,我必须使用:

httpclient.getConnectionManager().requestConnection(HttpRoute route, Object state);

这就是我卡住的地方。我假设对于路由我可以只使用new HttpRoute(new HttpHost("10.0.0.1")) 或我的服务器是什么,但是为Object state 输入什么?

其次,一旦我收到ClientConnectionManager,我就可以致电getConnection(long timeout, TimeUnit tunit)。但是从那里开始,我如何像以前对HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); 一样执行我的HttpGet httpRequest = new HttpGet(URL_TO_FILE);

我浏览了文档并尝试了很多不同的方法,但我无法获得可行的解决方案。因此,任何建议和/或代码示例都非常受欢迎。

【问题讨论】:

    标签: java android thread-safety connection-pooling httpclient


    【解决方案1】:

    您只需要拨打httpRequest.abort() 即可关闭连接。

    对于大文件,您必须有一个循环处理数据。您可以检查取消状态并从中中止,

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            while (instream.read(buf) >= 0) {
                if (cancelled)
                   httpRequest.abort();
                // Process the file
            }
         }
    

    当使用 pooling 或 keepalive 时,中止的连接不能返回到 pool 中,必须关闭。旧版本中存在一个错误,即连接保持活动状态,并且会弄乱下一个请求。我认为这一切都已解决。

    【讨论】:

    • 谢谢。这比我尝试做的要容易;-) 在 abort() 之后,连接不再出现在 netstat 中。我假设它已经关闭了。
    猜你喜欢
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 2013-04-25
    • 2018-12-24
    • 1970-01-01
    相关资源
    最近更新 更多