在做下载网络附件时,下载附件在本地Windows电脑上没有问题,不会卡主,但是当服务部署到Linux服务器上执行下载任务时,就会卡主。换了几种下载的写法,依然会卡主。这种情况偶尔也会不卡主。
int len;
byte[] buffer = new byte[1204];
while ((len = inputStream.read(buffer)) > 0) {
log.info("写入前");
outputStream.write(buffer, 0, len);
log.info("写入后");
}
outputStream.close();
inputStream.close();
log.info("下载完成");
每当卡主时,查看输出,是在read的时候。
这个问题困扰了好几天,因为在本地电脑上就可以,在服务器上就会卡主。今天找到原因了,是那两行close代码没有加上。因为这段代码是在在try catch中。我之前是在finally部分有判断如果不为空就关掉的,所以就没有在try里面去关闭了。今天在try里面加上了这两行,就不会卡主了,然后HttpURLConnection设置的读取超时也生效了。没有加上之前,感觉都没有生效。
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(60000);