AFNetworking预期内容错误

在故障块中得到json字符串:

NSURL *url = [[NSURL alloc] initWithString:@"http://www.vinipost.com/Services/Update/UpdateService.asmx/GetPropSubType?"];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];

        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

            NSLog(@"%@", JSON);
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
        }];
        [operation start];

输出:

Request Failed with Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {(
    "text/json",
    "text/javascript",
    "application/json",
    "text/html"
)}, got text/plain" UserInfo=0x71521a0 {NSLocalizedRecoverySuggestion=[{"PropTypId":1,"PropCatId":1,"PropTyp":"Flat/ Condo"}.......

这个错误表明 AFNetworking 在处理服务器返回的数据时发现它的内容类型与预期的不一致。具体来说,AFNetworking 期望的是某种形式的 JSON 格式(text/json、text/javascript、application/json 或 text/html),但是服务器返回的是 text/plain 类型的数据。


有几种可能的解决方法:

  • 如果服务器的响应的内容类型是正确的,那么检查你的代码是否正确地调用了 addAcceptableContentTypes: 方法。这个方法告诉 AFNetworking 可以接受哪些内容类型。
  • 如果服务器返回的内容类型是不正确的,那么你可以尝试更改服务器的设置,让它返回正确的内容类型。
  • 如果你希望 AFNetworking 能够处理 text/plain 类型的数据,那么你可以在调用 addAcceptableContentTypes: 方法之前调用 setDefaultContentType: 方法,将默认的内容类型设置为 text/plain。这样,AFNetworking 就可以正常地处理 text/plain 类型的数据了。