当前位置: 代码迷 >> 综合 >> okhttp response.body().contentLength()=-1
  详细解决方案

okhttp response.body().contentLength()=-1

热度:10   发布时间:2024-01-29 11:37:35.0

问题:

在使用okhttp下载文件的时候拿到的文件长度为-1

解决思路

1.看服务器返回的请求头是否含有Content-Length

cmd 打开命令窗口输入 curl -i +下载链接

窗口显示 connect-length 是有数值的

2.看返回的content-type 

content-type类型 https://www.runoob.com/http/http-content-type.html

第一个返回  text/plain; charset=utf-8 表示文本类型

第二个返回 application/octet-stream表示二进制数据库一般表示文件,第二个是可以可以拿到长度的

3.看自己代码中返回的请求头

chuncked 参考

 https://zhuanlan.zhihu.com/p/65816404

http://www.eit.name/blog/read.php?515

发现能显示的请求头里有Content-Length而不能显示长度的请求头里有没有content-type且多了Transfer-Encoding:chunked,在chuncked模式下是没有Content-Length的。

4.发现了问题 告知服务端,然后继续寻找解决办法,发现https://blog.csdn.net/z_sawyer/article/details/78668790在头部增加

addHeader("Accept-Encoding","identity")可以拿到Content-Length。identity表示不对内容编码,自然也不会采用chuncked模式。编码类型参考http://www.helpsd.net/library/networking/http/http-content-encoding/22 但是没有chuncked可能内容太老了。

 

  相关解决方案