【问题标题】:How to post json data to web server如何将json数据发布到Web服务器
【发布时间】: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


【解决方案1】:

替换下面的行

NSMutableDictionary *newDatasetInfo = @{
                              @"userName":@"abc",
                              @"passWord":@"1234",
                              @"apiKey":@"456789"
                              }.mutableCopy;     
 NSError *myError = nil;
NSData *post = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:NSJSONWritingPrettyPrinted  error:&myError];

NSDictionary *newDatasetInfo = @{
                                        @"userName":@"abc",
                                        @"passWord":@"1234",
                                        @"apiKey":@"456789"
                                        };

NSError *myError = nil;
NSData *post = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:0  error:&myError];

并确保您的所有参数(如用户名、密码等)都是真实的,请检查两次。您应该首先在postmanadvance rest client 中检查服务。这些是检查网络服务的不同工具。

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多