response expectedContentLength return -1(响应预期内容长度返回 -1)
问题描述
您好,当我从 Web 服务加载数据时,我需要创建一个 progressView.
Hello i need to create a progressView when i load data from my webservice.
实际上,expectedContentLength 总是返回 -1.
Actually the expectedContentLength alway return -1.
看了很多类似的问题后,看起来我的网络服务从未发送过 Content-Length:.
After look lots of similary problem it looks like my webservice never send the Content-Length:.
然后我用 CURL 检查,结果如下:
Then i check with CURL and here is the result :
< 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;
}
有人已经看到这个问题了吗?
Anyone have already see this problem ?
推荐答案
好的,我自己解决了,这是我真正的问题和解决方案:
Ok i've fix it myself here is my real problem and a solution :
当我用 Curl 询问时,我可以得到长度没问题.
When i ask with Curl i can get the length no problem.
但是当我使用 NSurlConnection 时
But when i use NSurlConnection
NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:req delegate:self];
响应将用Gzip"压缩(不要问我为什么).如果响应是用 Gzip 编码的,则不可能知道长度,然后expectedContentLength"返回-1.[response allHeaderFields] 中没有Content-Length".
The response will be compress with "Gzip" (don't ask me why). And if the response is encode with Gzip it's impossible to know the length, then "expectedContentLength" return -1. And "Content-Length" is absent from [response allHeaderFields].
如果你真的想获得长度,你可以简单地强制不要像这样使用 Gzip:
If you really want to get the length you can simply force to not use Gzip like this :
[req setValue:@"" forHTTPHeaderField:@"Accept-Encoding"];
这篇关于响应预期内容长度返回 -1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:响应预期内容长度返回 -1
基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01