AFNetworking 2.0标题内容类型未在POST调用时发送

时间:2015-04-28 15:45:51

标签: ios objective-c afnetworking-2

我试图将一些NSURLConnection代码转换为AFNetworking 2.0,并且我遇到了POST调用问题。 GET调用工作但不是POST。

这是我的代码:

+(void)login:(User*)myUser
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:myUser.username password:myUser.password];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [manager POST:URL_LOGIN
       parameters:nil
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSLog(@"success! Response = %@", responseObject);
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"failure. Error = %@", error);
          }];
}

这是我从服务器回来的错误:

Error Domain=com.<server>.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x7fe043c43670 {com.<server>.serialization.response.error.response=<NSHTTPURLResponse: 0x7fe043d52850> { URL: http://<server>/login.htm;jsessionid=98399EA8F090BF310D1CF5FD3C992A21?login_error=1 } { status code: 200, headers {
"Content-Language" = en;
"Content-Length" = 2801;
"Content-Type" = "text/html;charset=ISO-8859-1";
Date = "Tue, 28 Apr 2015 15:30:21 GMT";
Server = "Apache-Coyote/1.1";

我还试图将Content-Type明确地作为参数放置,但它也不起作用。

我在网上发现了很多建议,要么修改服务器(我不能这样做),要么只设置显然不起作用的manager.requestSerializer = [AFJSONRequestSerializer serializer];

对此的任何建议都将受到高度赞赏。此外,如前所述,此Content-Type的此通信适用于NSURLConnection和NSMutableURLRequest。

谢谢!

1 个答案:

答案 0 :(得分:2)

无论您是否愿意,您的服务器都会向您发送text / html。

因此,您必须在请求序列化程序中将其设置为可接受的内容类型。

您可以添加它,如下所示:

  manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];

或使用更通用的HTTP序列化程序,而不是JSON序列化程序,如下所示:

manager.responseSerializer = [AFHTTPResponseSerializer serializer];