我正在編寫需要與後端服務器通信的iPad應用程序。企業在使用這個後端的第一步是登錄,併爲這個服務器有一個我們可以張貼到一個URL,我這樣做:iOS:來自一個呼叫的兩個請求?
// Create the request.
NSString* loginURL = @"http://foo.local/signature/service/auth/rest/firewall/login";
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:loginURL]];
NSString* credentials = @"{\"userName\":\"[email protected]\", \"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調用,這是上面的代碼返回的。
爲什麼會發生這種情況?第一次與服務器的響應有關嗎?
您是否正在重定向? – Wain
是的,這絕對是一種可能性,IP地址是不同的。我應該如何處理? – easythrees
你怎麼沒有使用AFNetworking或其他網絡庫? –