【发布时间】:2016-05-02 07:35:11
【问题描述】:
我是 XCode 的新手。我想将一些数据发送到只能接受和发送 json 数据的 Web 服务器。所以我尝试了以下代码。
NSMutableDictionary *newDatasetInfo = @{
@"userName":@"abc",
@"passWord":@"1234",
@"apiKey":@"456789"
}.mutableCopy;
NSError *myError = nil;
NSData *post = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:NSJSONWritingPrettyPrinted error:&myError];
NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.HTTPAdditionalHeaders=@{
@"Accept":@"application/json"
};
NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig];
NSString *postdatalength=[NSString stringWithFormat:@"%lu",(unsigned long)[post length]];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc] init];
[request setURL:([NSURL URLWithString:@"http://xx.xx.xx.xx/efg/ijk/login"])];
[request setHTTPMethod:@"POST"];
[request setValue:postdatalength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:post];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"requestReply: %@", requestReply);
}];
[postDataTask resume];
但是在运行上面的代码后,我得到了以下消息
无法解析 POST 的 JSON。
有谁知道这里的错误是什么?请帮忙。
【问题讨论】:
-
为什么不使用 AFNetworking?
-
你看
myError的值了吗?post似乎是正确的吗?您不必为参数使用可变字典。
标签: ios objective-c json http-post