I am trying to pull HTTP headers and HTTP response code from a synchronous HTTP request on iPhone. Usually I have no problems with asynchronous requests, although there are few problems here. The HTTP response headers are null and the HTTP status code is 0. The web server is configured correctly and I can get the information I need in asynchronous requests. Here my code is copied to the command line program:
Problem # 1: [httpResponse allHeaderFields] returns nil.
Problem # 2: [httpResponse statusCode] returns 0.
I am mistaken in understanding that if there is an error that I now see 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?
#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; }
anon
source share