【问题标题】:response expectedContentLength return -1响应预期内容长度返回 -1
【发布时间】:2012-06-23 13:28:30
【问题描述】:

您好,当我从我的 web 服务加载数据时,我需要创建一个 progressView。

实际上,expectedContentLength 总是返回 -1。

看了很多类似的问题后,看起来我的网络服务从未发送过 Content-Length:.

然后我用 CURL 检查,结果如下:

< HTTP/1.1 200 OK
< Date: Thu, 21 Jun 2012 10:04:39 GMT
< Server: Apache/2.2.16 (Debian)
< X-Powered-By: PHP/5.3.3-7+squeeze9
< cache-control: no-cache
< Vary: Accept-Encoding
< Content-Type: text/html; charset=UTF-8
< Content-Length: 3239  
< Connection: Keep-Alive
< Set-Cookie: PHPSESSID=u4o4i9dofdgnkfmtnf163635j6; path=/

这是我捕捉长度的代码

long long expectDataSize;
long long currentDataSize;

....

 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
    NSLog(@"expect content length %lld", [response expectedContentLength]);
    expectDataSize = [response expectedContentLength];
    currentDataSize = 0;
}

有人已经看到这个问题了吗?

【问题讨论】:

标签: iphone ios5 nshttpurlresponse


【解决方案1】:

好的,我自己解决了,这是我真正的问题和解决方案:

当我用 Curl 询问时,我可以得到长度没问题。

但是当我使用 NSurlConnection 时

NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:req delegate:self];

响应将用“Gzip”压缩(不要问我为什么)。如果响应是用 Gzip 编码的,则不可能知道长度,然后“expectedContentLength”返回-1[response allHeaderFields] 中没有“Content-Length”。

如果你真的想得到长度,你可以简单地强制不要像这样使用 Gzip:

[req setValue:@"" forHTTPHeaderField:@"Accept-Encoding"];

【讨论】:

  • 'NSURLResponse'没有'allHeaderFields'属性。我怎么知道预期的长度?
  • 我使用的是 NSHTTPURLResponse,而不是 NSURLResponse
【解决方案2】:

我遇到了同样的问题,似乎预期的文件大小是未知的,这就是它返回-1的原因。

看到类似的威胁why [response expectedContentLength] always return -1

【讨论】:

    猜你喜欢
    • 2014-07-13
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    相关资源
    最近更新 更多