Parameters are always null when AFJSONRequestSerializer is used for a POST in AFNetworking

StackOverflow https://stackoverflow.com/questions/23613480

  •  20-07-2023
  •  | 
  •  

Pergunta

I'm writing a REST API by using SlimFramework in server side and AFNetworking in client side.

I'd like to add a value in Header for Authorization so that I'm using AFJSONRequestSerializer before the POST. Here is my code:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:self.apikey forHTTPHeaderField:@"Authorization"];

[manager POST:url parameters:@{REST_PARAM_USERID:    userId}
      success:^(AFHTTPRequestOperation *operation, id responseObject) {

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}];

But the failure callback is always called. I found that's because the parameters I passed to server are always null although they're not null when I debugged in my Xcode. When I comments out the requestSerializer then my server works well.I don't know what's the reason. Can anybody help? Thanks

Foi útil?

Solução

When you use AFJSONRequestSerializer, your parameters will always be serialized as JSON in the body of the HTTP request. If your server is not expecting JSON, then you should either reconfigure your server, or not use AFJSONRequestSerializer.

If, for some reason, you want to send some parameters through normal URL encoding, and others through JSON, you'll need to manually append them to your URL like so:

NSString *urlWithParams = [NSString stringWithFormat:@"%@?%@=%@", url, REST_PARAM_USERID, userId"];

[manager POST:urlWithParams parameters:@{@"some other" : @"params"}
  success:^(AFHTTPRequestOperation *operation, id responseObject) {

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}];
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top