我想在iOS中發送一個簡單的POST請求來測試我寫的服務器。我的代碼如下:使用NSURLSession的iOS POST請求
NSURL *url = [NSURL URLWithString:@"http://localhost:8888/createUser"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *bodyData = @"username=johndoe";
request.HTTPMethod = @"POST";
request.HTTPBody = [bodyData dataUsingEncoding:NSUTF8StringEncoding];
request.timeoutInterval = 5;
[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"resp: %@, err: %@", response, error);
}];
我一直在試圖調試這個,我很困惑。 completionHandler中的代碼永遠不會運行,請求永遠不會超時,並且服務器永遠不會看到任何內容。似乎沒有任何事情發生。我能夠使用舊的NSURLConnection
來請求一個請求,但是由於它已被棄用,我們希望避免這種情況。這裏有什麼問題?
你是不是想發送POST或GET?您分享的代碼是使用GET – josemando
我的錯誤 - 複製/粘貼錯誤後,我搞砸了。我正在嘗試發送POST。修正了我上面的代碼。 – user2871915