【问题标题】:-[NSURLRequest sendSynchronousRequest:returningResponse:error:] getting back HTTP headers-[NSURLRequest sendSynchronousRequest:returningResponse:error:] 取回 HTTP 标头
【发布时间】:2009-02-09 23:47:06
【问题描述】:

我正在尝试从 iPhone 上的同步 HTTP 请求中提取 HTTP 标头和 HTTP 响应代码。我通常对异步请求没有任何问题,尽管这里有点麻烦。 HTTP 响应标头为空,HTTP 状态代码为 0。Web 服务器配置正确,我可以在异步请求中检索我需要的详细信息。这是我复制到命令行程序的代码:

问题 #1:[httpResponse allHeaderFields] 返回 nil。
问题 #2:[httpResponse statusCode] 返回 0。

如果出现错误,我现在看到的错误是:Error Domain=NSURLErrorDomain Code=-1012 UserInfo=0x14b100 "Operation could not be completed. (NSURLErrorDomain error -1012.)",我无法访问 http 响应标头/状态代码?

#import <Foundation/Foundation.h>

int main (int argc, char *argv[])
{    

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSString *urlStr = @"http://tmp/myscript.php";
    NSString *postBody = @"foo=bar";   
    NSMutableURLRequest *request;
    NSData *postData = [postBody dataUsingEncoding:NSASCIIStringEncoding];
    NSError *error;
    NSURLResponse *response;
    NSHTTPURLResponse *httpResponse;
    NSData *dataReply;
    id stringReply;

    request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:urlStr]];

    [request setHTTPMethod: @"POST"];
    [request setHTTPBody:postData];
    [request setValue:@"text/xml" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  

    dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    stringReply = (NSString *)[[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];
    // Some debug code, etc.
    NSLog(@"reply from server: %@", stringReply);
    httpResponse = (NSHTTPURLResponse *)response;
    int statusCode = [httpResponse statusCode];  
    NSLog(@"HTTP Response Headers %@", [httpResponse allHeaderFields]); 
    NSLog(@"HTTP Status code: %d", statusCode);
    // End debug.

    [[NSRunLoop currentRunLoop] run];
    [pool release];
    return 0;
} 

【问题讨论】:

  • 你到底有什么问题?
  • 最后两个 NSLog 语句没有任何用处。 [httpResponse allHeaderFields] 返回零。 statusCode 返回 0。

标签: cocoa-touch


【解决方案1】:

您得到的错误代码是 NSURLErrorUserCancelledAuthentication,并记录在 Foundation Constants Reference 中。您可能正在尝试加载受密码保护的页面,在这种情况下,您可能需要在 URL 中添加用户名和密码。

【讨论】:

    【解决方案2】:

    问题 #1:[httpResponse allHeaderFields] 返回 nil。 问题 #2:[httpResponse statusCode] 返回 0。

    因为 httpResponse 为 nil,请参阅 here

    【讨论】:

      猜你喜欢
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多