iOS AFNetworking发布请求返回请求失败:错误请求(400)

时间:2016-09-04 09:12:28

标签: ios objective-c json afnetworking-3

我正在使用AFNetworking来呼叫后期网络服务,但每次我都收到回复

  

错误Domain = com.alamofire.error.serialization.response Code = -1011“请求失败:错误请求(400)”

这是我的代码

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
parameters:parameters
  progress:nil
   success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       success(task, responseObject);
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       failure(task, error);
   }];

它适用于邮递员。 Here is the request on postman 此外,我找到了很多类似错误的答案,但它没有解决任何问题。

1 个答案:

答案 0 :(得分:2)

您正在使用AFJSONRequestSerializer来序列化您的请求。这将创建一个JSON有效负载,而不是url编码的表单请求。

请尝试使用AFHTTPRequestSerializer

有关详细信息,请参阅文档here

您也可以删除以下代码行,正确的请求序列化程序将为您处理:

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