【发布时间】:2017-10-31 00:38:59
【问题描述】:
我正在尝试在 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
-
我的错误 - 在我搞砸之后复制/粘贴错误。我正在尝试发送 POST。修复了我上面的代码。
标签: ios post nsurlsession