Hesham Haleem Hesham Haleem - 1 year ago 175
JSON Question

iOS AFNetworking post request returns Request failed: bad request (400)

I am using AFNetworking to call a post web service, but every time i get the response

Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)"

Here is my code

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];

manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [self.responseSerializer.acceptableContentTypes setByAddingObject:@"application/json"];

[manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];

[parameters setObject:self.APIClientID forKey:@"client_id"];
[parameters setObject:self.APIClientSecret forKey:@"client_secret"];
[parameters setObject:self.APIGrantType forKey:@"grant_type"];

[manager POST:self.requestURL
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(task, responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(task, error);

It works in postman.
Here is the request on postman
Also, I found lot of answers for similar error, but it solved nothing.

Answer Source

You are using a AFJSONRequestSerializer to serialise your request. This will create a JSON payload and not a url encoded form request.

Try using AFHTTPRequestSerializer instead.

Refer to the documentation here for more information.

You can also remove the following line of code as well, the correct request serializer will handle that for you:

[manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];