如何在AFnetworking中设置内容类型

时间:2014-07-20 22:49:43

标签: ios objective-c json afnetworking content-type

我遇到了AFNetworking的问题。我无法将content-type设置为application/json。我能怎么做?我尝试了很多解决方案,但没有人工作过。这是你的代码:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  if (self.enableBasicAuth){
    [manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:[[SOWMerchant merchant]     username] password:[[SOWMerchant merchant] password]];
  }
  [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  manager.responseSerializer = [AFJSONResponseSerializer serializer];
  [manager POST:[NSString stringWithFormat:@"%@", url] parameters:postData success:^(AFHTTPRequestOperation *operation, id responseObject) {
    [self onSuccessResponse:responseObject request:operation];
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    [self onError:error request:operation];
  }];

我得到了这个回复

{ URL: https://sbengtest.spotonway.com:9099/v1.0/merchant/check }, response: <NSHTTPURLResponse:  0x10aa20530> { URL: https://sbengtest.spotonway.com:9099/v1.0/merchant/check } { status code: 400,     headers {
Connection = "keep-alive";
"Content-Length" = 192;
"Content-Type" = "text/html";
Date = "Sun, 20 Jul 2014 22:34:59 GMT";
Server = "nginx/1.2.1";
} }>

更新:

我试着添加这个

AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];

[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

operationManagerInstance.requestSerializer = requestSerializer;

我的应用崩溃

更新2: 有用。我删除了这一行

[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

2 个答案:

答案 0 :(得分:10)

这对我有用!

[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

答案 1 :(得分:6)

本准则工作

目标c

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

swift

manager.responseSerializer.acceptableContentTypes=NSSet (object: "text/html") as Set<NSObject>