欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HTTPS

程序员文章站 2022-07-13 21:17:35
...
#import "ViewController.h"

@interface ViewController () <NSURLSessionTaskDelegate>
@end
@implementation ViewController

- (void)httpsSessionTask{
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                                          delegate:self
                                                     delegateQueue:[[NSOperationQueue alloc] init]];
    NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"https://www.apple.com/"]
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                            NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                                        }];
    [task resume];
}


#pragma mark - <NSURLSessionTaskDelegate>
/**
 * challenge : 挑战、质询
 * completionHandler : 通过调用这个block,来告诉 URLSession 要不要接收这个证书
 */
-  (void)URLSession:(NSURLSession *)session
               task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
    
    // 如果不是服务器信任类型的证书,直接返回
    if (![challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) return;
    
    /*
        void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *)
        NSURLSessionAuthChallengeDisposition : 如何处理这个安全证书
        NSURLCredential : 安全证书
    */
    
    // 根据服务器的信任信息创建证书对象
    NSURLCredential *crdential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

    // 利用这个block说明使用这个证书
    if (completionHandler) {
        completionHandler(NSURLSessionAuthChallengeUseCredential, crdential);
    }
    
    !completionHandler ? : completionHandler(NSURLSessionAuthChallengeUseCredential, challenge.proposedCredential);
}

@end

就把苹果官方网站的首页抓取下来了

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US" prefix="og: http://ogp.me/ns#" class="">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=8; IE=9" />

... ...