我正在尝试将 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"]];
}
}
有什么建议么?