【问题标题】:NSURLResponse expectedContentLength -1NSURLResponse 预期内容长度 -1
【发布时间】:2013-10-08 17:47:30
【问题描述】:

我有一个 NSURLConnection 连接到我制作的 PHP API。该 PHP API 以数据响应。既然是动态应用,我这样做是为了告诉内容长度:

ob_start('scAPIHandler');    

function scAPIHandler($buffer){

    header('Content-Length: '.strlen($buffer));

    return $buffer;

}

在 API 文件的开头,然后输出任何必要的内容。然而,当

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 

函数触发,response.expectedContentLength 的值为 -1。当我尝试不连接到我的 PHP API,而是连接到网络上的一些图像时,会显示正确的预期内容长度。有什么方法可以让我的 PHP API 告诉 NSURLResponse 预期的内容长度?内容长度标头似乎不起作用。

提前致谢!

【问题讨论】:

    标签: php objective-c http-headers nsurlconnection content-length


    【解决方案1】:

    好的,我想通了。我用过

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
        NSDictionary *responseHeaders = ((NSHTTPURLResponse *)response).allHeaderFields;
    
        NSLog(@"headers: %@", responseHeaders.description);
    
    }
    

    这种方法可以找出我的 iOS 应用程序正在接收的标头,并将它们与连接到同一 URL 时 curl 打印的标头进行比较。事实证明,curl 显示的标题与 Objective-C 显示的标题之间存在差异。诚然,这让我很困惑,我不知道为什么会发生这种情况,但我找到了解决方案:

    ob_start('scAPIHandler');    
    
    function scAPIHandler($buffer){
    
        header('Custom-Content-Length: '.strlen($buffer));
    
        return $buffer;
    
    }
    

    Custom-Content-Length 确实出现在 Objective-C 中,我只是拿了我的自定义标头

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
        self.expectedContentLength = response.expectedContentLength;
        self.receivedData.length = 0;
    
        NSDictionary *responseHeaders = ((NSHTTPURLResponse *)response).allHeaderFields;
    
        if(self.expectedContentLength < 0){
    
            // take my own header
    
            NSString *actualContentLength = responseHeaders[@"Custom-Content-Length"];
    
            if(actualContentLength && actualContentLength.length > 0){
    
                self.expectedContentLength = actualContentLength.longLongValue;
    
            }
    
        }
    
    }
    

    并覆盖了预期的内容长度。

    【讨论】:

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