我正嘗試將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"]];
}
}
有什麼建議嗎?