iOS高级技术iOS技术栈iOS专攻资源__网络专题

使用NSURLSession或者AFN发送HTTPS请求

2017-03-12  本文已影响477人  小冰山口

HTTPS是基于HTTP的, 它与HTTP不同之处在于HTTP层和TCP层中间多了一个安全套接字层

HTTPS模型
HTTPS和HTTP的主要区别

HTTPS请求在客户端和服务器之间的交互过程

HTTPS模型

以上就是整个通讯过程

那么我们如何通过NSURLSession和AFN框架来发送HTTPS请求呢?

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self urlSession];
}

- (void)urlSession {
     /* 我们以购买火车票的url地址为例 */
    NSURL *url = [NSURL URLWithString:@"https://kyfw.12306.cn/otn/"];
    
     /* 发送HTTPS请求是需要对网络会话设置代理的 */
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    
    [dataTask resume];
}

当我们遵守了NSURLSessionDataDelegate的时候
会走- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler这么一个代理回调

challenge这个参数里有一个protectionSpace(受保护空间)这么一个属性,我们先打印一下看看有什么

打印内容

可以看到有主机名, 服务器请求方法, 认证方案, 端口443,代理,代理类型等内容. 我们可以看到认证方案为NSURLAuthenticationMethodServerTrust

当认证方案为NSURLAuthenticationMethodServerTrust这个时, 我们需要调用completionHandler这个block, 并传递两个参数

typedef NS_ENUM(NSInteger, NSURLSessionAuthChallengeDisposition) {
    NSURLSessionAuthChallengeUseCredential = 0,                                       /* Use the specified credential, which may be nil */
    NSURLSessionAuthChallengePerformDefaultHandling = 1,                              /* Default handling for the challenge - as if this delegate were not implemented; the credential parameter is ignored. */
    NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2,                       /* The entire request will be canceled; the credential parameter is ignored. */
    NSURLSessionAuthChallengeRejectProtectionSpace = 3,                               /* This challenge is rejected and the next authentication protection space should be tried; the credential parameter is ignored. */
}

我们选择第一个,使用证书

NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];

我们拿到这两个参数之后, 调用block,这样就完整地发送了一个HTTPS请求

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    if (![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
        return;
    }
    NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
    completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
    
}
运行结果如下
打印出了网页内容
- (void)afn {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    
    [manager GET:@"https://kyfw.12306.cn/otn/" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"请求失败:%@",error.localizedDescription);
        }
    }];
}

其他的都跟HTTP请求一样, 只是需要设置三个属性

这三个属性设置完毕之后, 就可以成功地发送HTTPS请求了.

运行结果:
运行结果
上一篇下一篇

猜你喜欢

热点阅读