最近写微服务,从服务端通过http协议下载文件并写入字节流。开始以为很简单。直接上手就来了,代码如下:
String szHttpFile="http://..../downlaod&&fileId="+fileId+"&&extra[action]=download&extra[ext]="+extName;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(szHttpFile).openConnection();
connection.setRequestMethod("GET");
int code = connection.getResponseCode();
if (code == 200 || code == 206) {
int contentLength = connection.getContentLength();
InputStream is = connection.getInputStream();
is.read(btData);
is.close();
}
} catch (IOException e) {
...
简单测试后,应用正常,以为没有问题。就提交了。过了几天用,大文件测试,发现不稳定,经常丢失字节流。而且不稳定。郁闷。后面研究InputStream .read()代码,发现了问题,在文件较大时,有拼接字符信息。所以read时,不一定能读取文件内容。需要采用以下方法才可以:
String szHttpFile="http://..../downlaod&&fileId="+fileId+"&&extra[action]=download&extra[ext]="+extName; try { HttpURLConnection connection = (HttpURLConnection) new URL(szHttpFile).openConnection(); connection.setRequestMethod("GET"); int code = connection.getResponseCode(); if (code == 200 || code == 206) { int contentLength = connection.getContentLength(); InputStream is = connection.getInputStream(); DataInputStream dataInputStream = new DataInputStream(is); dataInputStream.readFully(btData); dataInputStream.close(); is.close(); } } catch (IOException e) { ... }注意黑色加粗部分,是完全读取并处理的。后面发布和大数据测试正常。记录下来防止自己再犯类似错误,同时,也给遇到类似问题的朋友提供点解决问题的方法,相互学习交流和切磋。