我正在编写一个需要与后端服务器通信的 iPad 应用程序。使用这个后端的首要任务是登录,为此服务器有一个我们可以 POST 到的 URL,我这样做是这样的:
// Create the request.
NSString* loginURL = @"http://foo.local/signature/service/auth/rest/firewall/login";
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:loginURL]];
NSString* credentials = @"{\"userName\":\"foo2@foolinator.com\", \"password\":\"password\"}";
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[credentials dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES]];
// Logging in...
NSError* error = nil;
NSURLResponse* response;
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*) response;
NSString* responseString = [NSHTTPURLResponse localizedStringForStatusCode:[httpResponse statusCode]];
NSLog(@"Response String is: %@\n", responseString);
NSLog(@"Header fields are: %@\n", [httpResponse allHeaderFields]);
奇怪的是,我得到的响应是错误 405:不允许方法。如果我正在执行 GET,我会预料到这一点,但我正在执行 POST。
我安装了 WireShark 来检查 HTTP 请求,似乎实际上有两个请求。第一个是 POST 调用,服务器返回一些 cookie 信息作为响应,然后是第二个 GET 调用,这就是上面的代码返回的内容。
为什么会这样?是否与服务器第一次的响应有关?