我正在尝试使用 JSON POST 方法将一些数据发布到 Web 服务,我已经尝试了很多方法来做到这一点,但没有一个有效。这是我的代码,请检查:
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];
请检查。