首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AFNetworking + AFJSONRequestOperation + Rails

AFNetworking + AFJSONRequestOperation + Rails
EN

Stack Overflow用户
提问于 2012-03-03 17:02:18
回答 1查看 1.1K关注 0票数 1

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

如果我用:

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

然后:

代码语言:javascript
复制
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) 
  { 
    else {
    }
  } 

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

代码语言:javascript
复制
Parameters: {"contact"=>{"country_id"=>"45", "lastname"=>"Tutu"}}

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

因此,相反,我使用:

代码语言:javascript
复制
  NSMutableURLRequest *request = [[HTTPClient sharedClient] multipartFormRequestWithMethod:@"POST" path:path parameters:dict];

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

代码语言:javascript
复制
Parameters: {contact[country_id] => "45", contact[lastname] => "Tutu"} 

而不是

代码语言:javascript
复制
Parameters: {"contact"=>{"country_id"=>"45", "lastname"=>"Tutu"}}

我不明白为什么。当我不使用"constructingBodyWithBlock“块时,请求的主体似乎没有正确设置。

EN

回答 1

Stack Overflow用户

发布于 2012-03-06 10:54:33

不要使用multipartFormRequestWithMethod。

只需像这样使用postPath方法

代码语言:javascript
复制
[[YourHTTPClient sharedClient] postPath:path
   parameters:dict
      success:^(AFHTTPRequestOperation *operation, NSString* path){
      }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      }];

编辑:

如果您需要一个操作,直接使用AFJSONRequestOperation

代码语言:javascript
复制
+ (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) {
                                                }];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9547958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档