1

我有以下代码:

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://some-example-domain.com/api"]
                                          cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                      timeoutInterval:30.0];

[NSURLConnection sendAsynchronousRequest:theRequest
                                   queue: [NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           if (!error && data) {
                               // success!! - no errors and data returned
                               NSLog(@"success");
                           } else {
                               // error!! - something whent wrong
                               NSLog(@"failure: %@", [error localizedDescription]);
                           }

                       }
 ];

效果很好 -除了服务器只发送部分所需响应(例如来自 API 的 JSON 响应的一半)的奇怪情况(根据我的“if”语句它仍然是“成功的”)

有什么方法可以使用这种基于块的方法来检查接收到的数据是否完整?

我曾尝试研究 NSURLResponse *response - 但不能完全弄清楚如何使用它(或者,如果它在这种情况下确实有用)。关于如何测试块返回的“部分接收”数据的任何想法?

4

1 回答 1

1

此查询可能有两种不同的失败模式未处理,您需要单独检查它们:

  • "successful" HTTP connection, but an malformed response
  • "successful" HTTP connection, but status code indicates a problem on the server

In the case of NSURLConnection, the error is only set when the connection fails, not when a problem is reported from the server (for example: a 404 error or a 330 response).

Generally, when you are talking to an HTTP or HTTPS service, you'll need to check the -statusCode in the NSURLResponse, which in the case of these services will actually be an NSHTTPURLResponse. If there's an error on the server, such as 408 for request timed out on the server, you need to handle that separately from a connection failure (which will cause the error to be set).

Even if you get back a nice [response statusCode] == 200, you will likely still want to check for malformed responses, which you'll need to do when you parse the data that comes back. This is a less likely scenario, but if the server is flakey, you may get a partial response or an encoding failure.

于 2013-04-24T13:51:54.717 回答