2

我将两个 JSON 字典发送到一个 url。这适用于 NSURLRequest,但不适用于 ASIFormDataRequest。当使用 ASIFormDataRequest 发送相同的请求时,它会显示以下错误 -

{"Response":"Error","Code":"400","Detail":"无法解析 form.request 中的 JSON"}

下面是我与 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];
4

1 回答 1

0

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

NSDictionary *jsonDict = @{key:value,key:value};
NSData *requestData = [NSJSONSerialisation dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:error];
于 2013-03-20T09:15:52.953 回答