JSON请求使用NSURLRequest但不使用ASIFormDataRequest

时间:2013-03-20 07:25:08

标签: objective-c json asihttprequest afnetworking asiformdatarequest

我正在向网址发送两个JSON词典。这与NSURLRequest一起使用,但不与ASIFormDataRequest一起使用。当使用ASIFormDataRequest发送相同的请求时,它会显示以下错误 -

  

{“Response”:“Error”,“Code”:“400”,“Detail”:“无法解析JSON in   form.request“}

以下是我与ASIFormDataRequest一起使用的代码 -

NSString *request=[NSString stringWithFormat:@"REQUEST={\"request\":{\"api_username\":\"%@\", \"api_password\":\"%@\",\"method\":\"%@\"},",@"iphone",@"xlq229320#",@"getUser"];
NSString *methodParameter=[NSString stringWithFormat:@"\"methodparam\":{\"email\":\"%@\",\"password\":\"%@\"}}",@"ganesh@gmail.com",@"ganesh"];
NSString *finalRequest=[request stringByAppendingString:methodParameter];

NSMutableData* requestData = [NSMutableData dataWithBytes: [finalRequest UTF8String] length: [finalRequest length]];

ASIFormDataRequest *asiRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlForClinic]];

[asiRequest setTimeOutSeconds:60.0];
[asiRequest setPostBody:requestData];
[asiRequest setDelegate:self];
[asiRequest setRequestMethod:@"POST"];
[asiRequest setDidFailSelector:@selector(requestFailed:)];
[asiRequest setDidFinishSelector:@selector(requestFinished:)];
[asiRequest startAsynchronous];

我无法理解我做错了什么。如果有人对此有任何疑问,请告诉我。非常感谢。

我甚至尝试过使用AFNetworking,但它也没有用。这是代码 -

NSDictionary *dict1 = [[NSDictionary alloc]initWithObjectsAndKeys:@"iphone",@"api_username",@"xlq229320#",@"api_password",@"getUser",@"method", nil];
NSDictionary *dict2 = [[NSDictionary alloc]initWithObjectsAndKeys:@"ganesh@gmail.com",@"email",@"ganesh",@"password",nil];
NSMutableDictionary *req = [[NSMutableDictionary alloc]initWithObjectsAndKeys:dict1,@"request",dict2,@"methodparam",nil];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:req options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];    
NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString length]];

NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:urlForClinic] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:requestData];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
  NSLog(@"Public Timeline: %@ %@", JSON, response);
} failure:nil];

[operation start];

1 个答案:

答案 0 :(得分:0)

将要发送的数据格式化为NSDictionary中的键/值对,然后使用NSJSONSerialization创建需要发送的NSData对象。 它会更兼容。

NSDictionary *jsonDict = @{key:value,key:value};
NSData *requestData = [NSJSONSerialisation dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:error];