6

我在失败块中获取 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"}.......**
4

3 回答 3

10

操作前需要添加此行

[AFJSONRequestOperation addAcceptableContentTypes:
                            [NSSet setWithObject:@"text/plain"]];
于 2013-10-07T19:45:33.223 回答
5

错误很明显:Web 服务返回了错误的内容类型。内容类型应该是以下之一:

“文本/json”、“文本/javascript”、“应用程序/json”、“文本/html”

但它返回

文本/纯文本

此外,如果您查看 http 响应,它会在其中返回 HTML TAGS,因此 AFNetworking 无法解析。

如果这个页面:

http://www.vinipost.com/Services/Update/UpdateService.asmx/GetPropSubType?

在您的控制之下,更正删除 html 标记和更改内容类型的行为

于 2013-07-15T06:49:51.520 回答
4

在 AFNetworking 中,您必须在 AFHTTPClient 的帮助下创建 NSURLRequest(所以首先您必须创建 AFHTTPClient 并且必须为此对象设置一些属性),如下所示

AFHTTPClient *httpClient = [[httpClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.vinipost.com/"]];

[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [httpClient setDefaultHeader:@"Accept" value:@"application/json"];
    httpClient.parameterEncoding = AFJSONParameterEncoding;

现在,如果取决于 GET/POST 或任何其他类型的请求,您需要设置参数我认为它是 POST 请求,所以设置参数字典并正确设置所有必需的键值对。如果不需要参数,您可以将参数传递为nil

NSURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"Services/Update/UpdateService.asmx/GetPropSubType?" parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                     success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
                                     {
                                         NSLog(@"%@",JSON);

                                     }
                                     failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
                                     {
                                         NSLog(@"Error MSG = %@",error);
                                     }];

[operation start];

希望这对你有用:)

于 2013-07-15T06:59:48.357 回答