我正尝试将JSON格式的数据发送到REST API。发送参数时,Web服务不会返回任何数据,而是会给出以下错误:解析JSON时出错:错误域= NSCocoaErrorDomain代码= 3840“操作无法完成(可可错误3840.)”(JSON文本没有不以数组或对象和选项开始,以允许片段未设置。)ios5:使用POST将JSON数据从iPhone发送到REST
这是因为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"]];
}
}
有什么建议吗?