1

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

2
  • Is your server expecting to parse JSON? Commented May 13, 2014 at 0:43
  • What are the values and class types of REST_PARAM_USERID and userId? Commented May 13, 2014 at 0:43

1 Answer 1

1

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) { }]; 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer. I think I got what you mean.The reason I'm using AFJSONRequestSerializer is that I want to pass a string inside my http header? If there is another way to do that?
I'm using Slimframework in my server side. I'm not very sure it support JSON parameters or not. Have to check the document.
You don't need to use AFJSONRequestSerializer for that. The request serializer determines the body format, and has almost nothing to do with the headers. If you want to set an HTTP header, use [manager.requestSerializer setValue:@"some value" forHTTPHeaderField:@"some-http-header"];. You can do this on any serializer.
Thanks. I understand now. And Yes, If I don't use AFJSONRequestSerializer, the POST parameters will be received by server side.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.