iOS HTTPS安全请求 验证服务器返回的证书

iOS HTTPS安全请求 验证服务器返回的证书

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self httpsSession];
    
}


- (void)httpsSession {
    
    // 创建session
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    // session发起任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://www.microsoft.com/zh-cn/software-download/windows10ISO"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    // task开启任务
    [dataTask resume];
}

#pragma mark - <NSURLSessionTaskDelegate>
// 与服务器建立安全连接,(服务端返回证书给客户端、客户端使用证书加密数据发送给服务端)
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    
    // challenge:质问(保护空间、认证方法==ServerTrust)
    // NSURLSessionAuthChallengeDisposition:如何处理这个安全证书
    // NSURLCredential:安全证书
    if (challenge.protectionSpace.authenticationMethod != NSURLAuthenticationMethodServerTrust) {
        return;
    }
    // 根据服务端的的信任信息,创建证书
    NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
    completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    NSLog(@"-------completionHandler");
}


猜你喜欢

转载自blog.csdn.net/wenzfcsdn/article/details/53642952
今日推荐