tags:

views:

4210

answers:

1

I'm trying to pull out HTTP Headers and an HTTP Response Code from a synchronous HTTP request on the iPhone. I generally don't have any issues doing this with asynchronous requests, although a bit of trouble here. The HTTP Response Headers are null and HTTP Status Code is 0. Web server is configured proper and I can retrieve the details I need in an asynchronous requests. Here's my code copied out to a command line program:

Problem #1: [httpResponse allHeaderFields] returns nil.
Problem #2: [httpResponse statusCode] returns 0.

Am I wrong in understanding that if there is an error, which I'm now seeing as: Error Domain=NSURLErrorDomain Code=-1012 UserInfo=0x14b100 "Operation could not be completed. (NSURLErrorDomain error -1012.)", that I do not get access to http response headers/status code?

#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;
}
+2  A: 

The error code you got is NSURLErrorUserCancelledAuthentication and is documented in Foundation Constants Reference. You might be trying to load a password-protected page, in which case you may have to add a username and password to the URL.

Chris Lundie