我想用JSON POST方法發佈一些數據到Web服務,我已經嘗試了很多方法來做到這一點,但沒有工作。這裏是我的代碼,請檢查:JSON POST不工作在iOs
NSArray *objects=[NSArray arrayWithObjects:@"value1", @"value2",@"value3", @"value4",@"value5", @"value6",@"value7", @"value8",@"value9", nil] ;
NSArray *keys=[NSArray arrayWithObjects:@"FirstName", @"LastName",@"UserName", @"Password",@"Email", @"Gender",@"DeviceId", @"DeviceName",@"ProfileImage", nil];
NSData *_jsonData=nil;
NSString *_jsonString=nil;
NSURL *url=[NSURL URLWithString:urlstring];
NSDictionary *JsonDictionary=[NSDictionary dictionaryWithObjects:objects forKeys:keys];
if([NSJSONSerialization isValidJSONObject:JsonDictionary]){
_jsonData=[NSJSONSerialization dataWithJSONObject:JsonDictionary options:0 error:nil];
_jsonString=[[NSString alloc]initWithData:_jsonData encoding:NSUTF8StringEncoding];
}
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
// [request setHTTPBody:_jsonData];
// [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
// [request setValue:[NSString stringWithFormat:@"%d", [_jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSString *finalString = [_jsonString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
[request setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
// //return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
請檢查。
當我提交服務器,在它顯示的服務器上,缺少'{'和'}'。 – Mithuzz
@Mithuzz由於您沒有提供任何有關後端基礎架構的信息,因此無法提供更多幫助。請求到達服務器的事實更多地指向那裏有問題,而不是在客戶端。 –
只是要清楚,在你的代碼中,你沒有爲「NSJSONSerialization」設置選項嗎? –