【问题标题】:AFHTTPRequestOperation nil response instead of errorAFHTTPRequestOperation 无响应而不是错误
【发布时间】:2012-09-09 04:32:25
【问题描述】:

我正在使用 AFHTTPRequestOperation 来解析几个 HTML 页面。 我遇到的问题是,如果我使用了错误的端口号,例如,当连接到服务器时,“失败”错误块不会触发。相反,完成块触发但响应字符串为零。 我只是从 ASIHTTP 切换到 AFNetworking,而使用 ASIHTTP 这会产生错误。

这肯定会提供错误吗?我怎样才能捕捉到这个?

    NSString *urlString;
    urlString = [NSString stringWithFormat:@"%@://%@:%@/",kHttp,_IP,_Port];
    NSURL *url = [NSURL URLWithString:urlString];

    // Set authorization
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
    [httpClient setAuthorizationHeaderWithUsername:_User password:_Pass];

    NSURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"Info.htm" parameters:nil];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([self parseInfoLive:operation.responseString])
            _count_parsed++;
        if (_count_parsed == 2)
            [[NSNotificationCenter defaultCenter] postNotificationName:@"downloadsComplete" object:nil];
    }
                                     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                         NSLog(@"Error during connection: %@",error.description);
                                         [[NSNotificationCenter defaultCenter] postNotificationName:@"errorConnecting" object:nil];
                                     }];
[operation start];

【问题讨论】:

  • 您可以在成功块中添加一个检查来验证结果数据(检查是否为零)。您也可以将 AFHTTPRequestOperation 子类化来执行此操作,并针对这些情况跳入错误块。
  • 是的,我可能会这样做。我想知道为什么我没有收到错误,但是我测试的端口在 safari 中给出了一个空白页,所以我想这毕竟不是错误。
  • 是的,空结果不算作 HTTP 错误 - 去过那里,拿到 T 恤 ;)

标签: ios xcode nsurl nsurlrequest afnetworking


【解决方案1】:

这似乎是 AFNetworking 中的一个错误,即使是在这个问题发生 2.5 年后。当响应包含特殊字符时会发生这种情况(它可以显示为空格,因为有时甚至文本查看器也无法解析它)。您可以尝试将收到的 JSON 字符串转换为 NSUTF8StringEncoding,然后根据需要将其用作 NSData。

NSURL *url = <YOUR REQUEST URL>
NSString *data = [NSString stringWithContentsOfURL:url];
NSData *metOfficeData = [data dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = [NSError new];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:metOfficeData options:kNilOptions error:&error];

【讨论】:

    猜你喜欢
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    相关资源
    最近更新 更多