0

I am trying to pass two different parameters on the POST Request in Objective-C.

The first parameters should be placed on the Header while the other one should be placed on the Body.

NSDictionary *headerParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                    @"password", @"grant_type",
                                    @"write", @"scope", nil];
NSDictionary *bodyParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                    username, @"username",
                                    password, @"password", nil];
AFHTTPRequestSerializer *r = [AFHTTPRequestSerializer serializer];
NSError *error = nil;

NSData *requestBody = [NSKeyedArchiver archivedDataWithRootObject:bodyParams];

NSMutableURLRequest *request = [r requestWithMethod:@"POST" URLString:urlString parameters:headerParams error:&error];
[request setValue:[NSString stringWithFormat:@"application/json,application/x-www-form-urlencoded"] forHTTPHeaderField:@"Accept"];
[request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded"] forHTTPHeaderField:@"ContentType"];
[request setHTTPBody: requestBody]; //--> If I comment this, the headerParams doesn't removed

If I debug the above code with this statement :

po [[NSString alloc] initWithData: request.HTTPBody encoding:4]

I got nil. But when I omit the [request setHTTPBody: requestBody];'s part, I got the headerParams 's value. I would like to get both headerParams and bodyParams 's value. What's wrong? Thanks.

Swati
  • 2,870
  • 7
  • 45
  • 87
mrjimoy_05
  • 3,452
  • 9
  • 58
  • 95

1 Answers1

1

By looking at the documentation for AFHTTPRequestSerializer regarding the parameters parameter:

parameters
The parameters to be either set as a query string for GET requests, or the request HTTP body.

The dictionary that you think will go to the headers of the request will actually go to it's body. And the setHTTPBody: call from the last line of your code will overwrite this value.

If you want the first headerParams dictionary to go to the request headers, you'll need to use setValue:forHTTPHeaderField:.

Cristik
  • 30,989
  • 25
  • 91
  • 127
  • No problem. Remember: when something doesn't behave as you'd expect, go to the documentation, it might shed some light on the problem. – Cristik Jan 12 '16 at 08:15