1.问题产生场景
1.)Android客户端需要更新APP,使用URLconnection下载最新的APP文件进行安装
/**
* 文件下载
* @return
*/
private long download() {
URLConnection connection = null;
int bytesCopied = 0;
try {
connection = mUrl.openConnection();
//参照 https://blog.csdn.net/fighting_2017/article/details/93972909
connection.setDoOutput(true);
int length = connection.getContentLength();
mOutputStream = new ProgressReportingOutputStream(mFile);
publishProgress(0, length);
bytesCopied = copy(connection.getInputStream(), mOutputStream);
mOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bytesCopied;
}
2.解决思路
java使用URLconnection下载文件 getContentLength()为-1 的解决办法_Erorrs的博客-CSDN博客_getcontentlength于是参照了这位大佬博客分析原因是请求的类型有变化,我更改之后connection.getContentLength();任然返回 -1;
这说明我和他遇到的可能不是同一个问题(感谢分享)。
最后检查连接发现是URL中含有中文编码,同样的连接在浏览器上打开居然能下载(其实浏览器也对中文做了编码处理,而Android客户端可能不会去处理)。
参照这位大佬的博客的解决方案是:请求之前对URL进行编码Android url中文编码问题 - 狂奔的小狮子 - 博客园
private String encodeUrl(String url) {
return Uri.encode(url,"-![.:/,%?&=]");
}
参考文章:java使用URLconnection下载文件 getContentLength()为-1 的解决办法_Erorrs的博客-CSDN博客_getcontentlength
参考文章:Android url中文编码问题 - 狂奔的小狮子 - 博客园
测试完成~