[英]Java interrupt inputstream without close() method
因此,我有一段代码可以连接到服务器,并以2mb的块下载约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.close()
或req.abort()
而不是调用res.getEntity().getContent().close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.