没有close()方法的Java中断输入流

标签 java apache http iostream

所以,我有一段代码可以连接到服务器并以 2mb block 的形式下载大约 2gb 的内容。所有这些都是在线程中完成的。有时我需要停止线程,因为主线程中发生了不同的错误,或者我想关闭应用程序。我的问题是我无法关闭连接的 InputStream。每次我调用 close() 方法时,InputStream 都会消耗服务器发送的整个 2gb。 有没有办法在不消耗服务器发送的全部内容的情况下关闭 InputStream?

fos.getChannel().transferFrom(Channels.newChannel(res.getEntity().getContent()), bytes_read, CHUNK_SIZE);
res.getEntity().getContent().close();

res.getEntity().getContent()返回从连接创建的 InputStream。

res 是一个 apache httpResponse。

fos 是我要保存响应内容的FileOutputStream。

编辑:线程的运行方法

CHUNK_SIZE: int: 2mb 字节

@Override
public void run() {
    int expectedCode;
    do{
        try {
            client = HttpClients.createDefault();

            HttpGet req = new HttpGet(url.toString());
            HttpResponse res = client.execute(req);

            if (res.getStatusLine().getStatusCode() == 200) {
                while(running){
                    fos.getChannel().transferFrom(Channels.newChannel(res.getEntity().getContent()), bytes_read, CHUNK_SIZE);
                }
            } else {
                log.error(Languages.getString("Download.2") + expectedCode); //$NON-NLS-1$
            }
        } catch (Exception ex) {
            log.error(ex);
        } finally{
            try{
                rbc.close();
            } catch(Exception ex){
                log.error(ex);
            }
        }
    }while(!isFinished() && running);
    try{
        rbc.close();
        fos.close();
        client.close();
    } catch(Exception ex){
        log.error(ex);
    }
}

最佳答案

Apache HttpClient 的底层实现使用 ContentLengthInputStream 来保持响应。如 ContentLengthInputStream 中所述,.close() 方法实际上从未关闭流,而是读取所有剩余字节,直到达到 Content-Length。

解决方案:不要调用 res.getEntity().getContent().close(),而是尝试 res.close()req.abort( )

关于没有close()方法的Java中断输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40947622/

相关文章:

java - 为什么这个PreparedStatement会抛出mysql错误?

java - Java 中的组合框 - 空指针

java - 具有多个模块的 tomcat-maven-plugin 和 pluginManagement

regex - Apache2conf重定向

linux - Apache 服务器上的 403 错误

javascript - 如何在 Javascript 中从 Vert.x 服务器接收 websocket 消息?

java - 有没有另一种方法可以不使用数组的索引来获取索引?前任。不使用数组[5]

linux - 页面未加载 IP 地址

c# - 简单的 C# Http/TCP 服务器

java - 最佳实践 在为 Web 项目创建 Solr HttpSolrServer 对象的对象时