1

我在使用 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"}}

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

4

1 回答 1

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) {
                                                }];
于 2012-03-06T10:54:33.280 回答