getContentLength() 仅在 WiFi 中返回 -1? [英] getContentLength() return -1 only in WiFi?

查看:34
本文介绍了getContentLength() 仅在 WiFi 中返回 -1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道文件的长度,所以我尝试了getContentLength().它在网络连接 (edge/3g) 下工作正常,但在 WiFi 下返回 -1?
为什么?WiFi很好,找到了文件,可以下载,但是getContentLength()的返回总是-1".我不明白.file 是谷歌文档文件.
还有其他方法可以得到长度吗?

I want to know the length of the file, so I tried getContentLength(). It works fine with network connection (edge/3g) but returns -1 with WiFi?
Why? The WiFi is good and the file was found, it can be downloaded but the return of getContentLength() is always "-1". I dont understand. file is a google documents file.
Is there an other way to get the length?

我的代码是:

URL url = new URL(file);

URLConnection conexion = url.openConnection();

conexion.connect();

int poids = conexion.getContentLength();

推荐答案

服务器可能正在发回分块的 HTTP 响应.

The server is probably sending back a HTTP response that is chunked.

getContentLength() 方法的行为是返回内容长度的内部"值,这是可用的.当客户端收到一个 HTTP 分块响应时,响应的长度是未知的,因此内容长度值被标记为 -1.

The behavior of the getContentLength() method is to return the 'internal' value of the length of the content, that is available to it. When the client receives a HTTP chunked response, the length of the response is not known, and hence the content length value is marked as -1.

响应的分块性质可以由 Transfer-Encoding 标头值决定;分块响应的值为分块.如果响应是通过分块编码发送的,则 HTTP 服务器不需要提供 Content-Length 标头值;事实上,鼓励服务器不要为分块响应发送 Content-Length 标头,因为客户端应该忽略 Content-Length 标头.

The chunked nature of the response can determined by the Transfer-Encoding header value; chunked responses have a value of chunked. HTTP servers need not provide a Content-Length header value if the response is sent via chunked encoding; in fact, servers are encouraged to not send the Content-Length header for a chunked response, for the client is supposed to ignore the Content-Length header.

至于服务器在两个网络中响应不同的实际原因,这取决于各种因素.通常服务器会选择更优化的交付模式,这取决于客户端的性质.出于某种原因,它检测到最好为一种类型的连接发送分块响应.答案可能在于 HTTP 请求标头,但不一定如此.

As for the actual reason on why the server is responding differently in two networks, well it depends on various factors. Usually servers will opt for a more optimal delivery mode, depending on the nature of the client. For some reason, it has detected that it is better off sending chunked responses for one type of a connection. The answer might lie in the HTTP request headers, but not necessarily so.

这篇关于getContentLength() 仅在 WiFi 中返回 -1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆