【问题标题】:ios5: Sending JSON data from the iPhone to REST using POSTios5:使用 POST 将 JSON 数据从 iPhone 发送到 REST
【发布时间】:2012-06-28 21:10:10
【问题描述】:

我正在尝试将 JSON 格式的数据发送到 REST api。发送参数时,Web 服务不返回任何数据,而是给出以下错误:解析 JSON 时出错:Error Domain=NSCocoaErrorDomain Code=3840 “无法完成操作。(Cocoa 错误 3840。)”(JSON 文本没有不以数组或对象开头,并允许未设置片段的选项。)

这是因为 Web 服务无法读取参数。 但是,如果我将此参数直接添加到 URL,则会返回正确的结果例如:http://localhost:8080/de.vogella.jersey.final/rest/notes/63056

以下是发送参数的代码:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost:8080/de.vogella.jersey.final/rest/notes/"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

    NSString *postString = @"{\"notes\":\"63056\"}";
    NSLog(@"Request: %@", postString);
   // NSString *postString = @"";


    [request setValue:[NSString stringWithFormat:@"%d",[postString length]] forHTTPHeaderField:@"Content-length"];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];




    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
    NSLog(@"Return Data%@",returnData);


    //Getting the task types from the JSON array received  
    NSMutableArray *jsonArray =[NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
    NSLog(@"jsonArray is %@",jsonArray);
    taskTypes =[[NSMutableArray alloc]init ];
    if (!jsonArray) {
        NSLog(@"Error parsing JSON: %@",error);
    } else {
        for(NSDictionary *taskType in jsonArray) {


            [taskTypes addObject:[taskType objectForKey:@"TaskName"]];
        }

    }

有什么建议吗?

【问题讨论】:

    标签: json ios5 http-post


    【解决方案1】:

    您的错误“JSON 文本没有以数组或对象开头,并且允许未设置片段的选项”可能意味着两件事:

    1. 您指定的是您希望响应对象为 JSON 格式,但事实并非如此(例如,如果您使用 AFJSONRequestOperation 并且服务器返回 JSON 以外的其他内容,则会发生这种情况)

    修复:获取服务器代码并确保它返回有效的 JSON 对象

    1. 您尚未指定可以接收 JSON 以外的内容

    修复:如果您使用的是 AFNetworking,请将 NSJSONReadingAllowFragments 传递给您的 AFHTTPClient 子类上的 [NSJSONSerialization JSONObjectWithData:options:error:](请向Cocoa error 3840 using JSON (iOS) 寻求此答案)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多