Android使用URLconnection下载文件getContentLength()为-1

​​​​​​​ 

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中文编码问题 - 狂奔的小狮子 - 博客园

测试完成~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值