我对Objective C很新,甚至更新的网络API,如NSMutableURLRequest和NSURLSession。无论如何,我在调用异步API以POST到HTTPS地址并获取JSON数据包时遇到问题:
我可以从命令行调用curl并成功获取这样的数据包:
curl -X POST -H "Content-Type: application/json" -d '{"name":"foo","pass":"bar"}' --insecure https://bla bla bla.com/xxxx
并获取一个json数据包以响应curl:
"{'key1':'val1','key2':'val2','key3':'val3'}
我想在Objective C中做相同的事情。 这就是我到目前为止所做的:
#define USER_URI @"https://bla bla bla.com"
NSDictionary* gistDict = [NSDictionary dictionaryWithObjectsAndKeys:
username, @"name",
password, @"pass", nil];
NSError* jsonError;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:gistDict options: NSJSONWritingPrettyPrinted error: &jsonError];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: USER_URI]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:jsonData];
NSURLSession* session = [NSURLSession sharedSession];
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler: ^(NSData* data, NSURLResponse* response, NSError* error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse *)response;
BOOL success = data && httpResponse.statusCode == 200;
if (success) {
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: nil];
NSLog(@"json dict %@", jsonDictionary);
}
}];
问题出在运行时:数据为0字节,响应为零。块参数error
返回一条消息:
Error Domain=NSURLErrorDomain Code=-1202 "The operation couldn’t be completed.
这是因为我要发布到HTTPS网址而不是HTTP网址吗?