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

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

  •  20-07-2023
  •  | 
  •  

문제

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

도움이 되었습니까?

해결책

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) {

}];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top