2012-03-03 57 views
1

我在使用AFJSONOperationRequest之前使用NSMutableURLRequest,并且在我的Rails应用程序中获取数据时遇到问题。AFNetworking + AFJSONRequestOperation + 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”。

+0

和仍然找不到解决方案。你能不能找出问题所在?哦...对我来说,它不适用于constructBodyWithBlock部分... – Dennis 2012-03-29 05:46:59

回答

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) { 
               }]; 
+0

是的,但我在我的模型中构建请求...那么如何做到这一点与请求和AFJSONRequestOperation? – 2012-03-06 11:30:16