下载的时候,莫名奇妙的不能下载在本地。如图下边
HttpURLConnection conn = null;
RandomAccessFile raf = null;
try {
URL url = new URL(mFileInfo.getUrl());
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
int length = -1;
if (code == HttpURLConnection.HTTP_OK) {
length = conn.getContentLength();
}
if (length <= 0) {
return;
}
File dir = new File(DownloadPath);
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir, mFileInfo.getFileName());
raf = new RandomAccessFile(file, "rwd");
raf.setLength(length);
mFileInfo.setLength(length);
Message msg = Message.obtain();
msg.obj = mFileInfo;
msg.what = MSG_INIT;
mHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
try {
if (raf != null) {
raf.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
经过断点发现会走这步
if (length <= 0) {
return;
}
此时length 是为0,为什么会为0呢?
if (code == HttpURLConnection.HTTP_OK) {
length = conn.getContentLength();
}
getContentLength()是没有获取到
然后添加一行
conn.setRequestProperty(“Accept-Encoding”, “identity”);
因为Accept-Encoding:HTTP请求头,标识客户端能够理解的内容编码方式,通常是一种压缩算法,如:gizp,deflate,compress,identity… 客户端向服务端发送该请求头,示意服务端如果需要编码只能用这些编码方式,当然也有可以不用。无论用还是不用,服务端需要在响应头中加入Content-Encoding,其中identity标识未使用编码
可以解决getContentLength()为0,没有下载的问题。
如有不对的欢迎评论