AFNetworking + AFJSONRequestOperation + Rails

时间:2012-03-03 17:02:18

标签: ruby-on-rails afnetworking

我在使用AFJSONOperationRequest之前使用的是NSMutableURLRequest,我在使用Rails应用程序获取数据时遇到了问题。

如果我使用:

  NSMutableURLRequest *request = [[HTTPClient sharedClient] multipartFormRequestWithMethod:@"POST" path:path parameters:dict constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) 
  {
  }]; 

然后:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) 
  { 
    else {
    }
  } 

我在Rails日志中正确格式化了数据:

Parameters: {"contact"=>{"country_id"=>"45", "lastname"=>"Tutu"}}

但我不需要AFMultipartFormData来发送文件......(没有要发送的文件)

所以,相反,我使用:

  NSMutableURLRequest *request = [[HTTPClient sharedClient] multipartFormRequestWithMethod:@"POST" path:path parameters:dict];

还有我的AFJSONRequestOperation。但是,我的参数现在没有在我的rails应用程序中正确设置:

Parameters: {contact[country_id] => "45", contact[lastname] => "Tutu"} 

而不是

Parameters: {"contact"=>{"country_id"=>"45", "lastname"=>"Tutu"}}

我不明白为什么。当我不使用块时,看起来请求的主体没有正确设置:“constructBodyWithBlock”。

1 个答案:

答案 0 :(得分:0)

不要使用multipartFormRequestWithMethod。

只需像这样使用postPath方法

[[YourHTTPClient sharedClient] postPath:path
   parameters:dict
      success:^(AFHTTPRequestOperation *operation, NSString* path){
      }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      }];

修改

如果需要操作,请直接使用AFJSONRequestOperation

+ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
                                                success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success 
                                                failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;


NSURL *url = [NSURL URLWithString:@"http://yoursite.com/path"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                                                }
                                                failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                                                }];