使用NSURLSession处理HTTP错误? [英] Handle HTTP error with NSURLSession?

查看:346
本文介绍了使用NSURLSession处理HTTP错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 NSURLSession 发送HTTP请求。它工作正常,但当服务器没有响应时,我找不到HTTP错误代码的存储位置。 completionHandler 的第三个参数只是一个非常通用的 NSError 。我读了 NSURLResponse 的参考资料,但一无所获。

I'm trying to send a HTTP request with NSURLSession. It works fine, but when the server doesn't respond I can't find where the HTTP error code is stored. The third parameter of completionHandler is just a very general NSError. I read the reference of NSURLResponse but found nothing.

NSURLSessionDataTask *dataTask =
    [session dataTaskWithRequest:[self postRequestWithURLString:apiEntry parameters:parameters]
         completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
             if(!error) NSLog([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);    
         }
    ];
[dataTask resume];


推荐答案

的第二个参数completionHandler NSURLResponse ,在执行HTTP请求时,通常是 NSHTTPURLResponse 。所以,你通常会做类似的事情:

The second parameter of the completionHandler is the NSURLResponse, which when doing a HTTP request, is generally a NSHTTPURLResponse. So, you'd generally do something like:

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:[self postRequestWithURLString:apiEntry parameters:parameters] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    // handle basic connectivity issues here

    if (error) {
        NSLog(@"dataTaskWithRequest error: %@", error);
        return;
    }

    // handle HTTP errors here

    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {

        NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];

        if (statusCode != 200) {
            NSLog(@"dataTaskWithRequest HTTP status code: %d", statusCode);
            return;
        }
    }

    // otherwise, everything is probably fine and you should interpret the `data` contents

    NSLog(@"data: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
[dataTask resume];

这篇关于使用NSURLSession处理HTTP错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆