使用NSURLSession或者AFN发送HTTPS请求

1642625972 7年前
   <p>HTTPS是基于HTTP的, 它与HTTP不同之处在于HTTP层和TCP层中间多了一个 <strong>安全套接字层</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/ed163ed043f3fb735d30fcab67cbe438.png"></p>    <p>HTTPS模型</p>    <p>HTTPS和HTTP的主要区别</p>    <ul>     <li>HTTPS协议需要到CA(证书发布机构)申请证书</li>     <li>HTTP是明文传输, HTTPS则是具有SSL加密传输协议</li>     <li>连接方式不同,所用端口,HTTP是80端口,HTTPS是443端口</li>    </ul>    <p>HTTPS请求在客户端和服务器之间的交互过程</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/ca2ed9800453c25615bdb1fe16c00acf.png"></p>    <p>HTTPS模型</p>    <ul>     <li> <p>简单说来, 就是在客户端和服务器之间建立一个安全通道, 建立通道的机制就是公钥和私钥, 但是服务器如何将公钥传给客户端呢? 如何保证公钥在传输的过程中不会被拦截呢? 这就需要CA颁发数字证书了.</p> </li>     <li> <p>数字证书你可以理解为一个被CA用私钥加密了服务器端公钥的密文</p> <p>当服务器拿到了这个密文之后就可以发送给客户端了, 即使被拦截,没有CA的公钥也是无法解开的</p> </li>     <li> <p>当客户端拿到了服务器端的公钥了之后, 对数据进行公钥加密发送给服务器端, 服务器端进行私钥解密.</p> </li>     <li> <p>当服务器端要返回数据给客户端时, 先用私钥加密,传输给客户端之后, 客户端再用公钥解密</p> </li>    </ul>    <p>以上就是整个通讯过程</p>    <p>那么我们如何通过NSURLSession和AFN框架来发送HTTPS请求呢?</p>    <ul>     <li>先说NSURLSession</li>    </ul>    <pre>  <code class="language-objectivec">- (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];  }</code></pre>    <p>当我们遵守了 NSURLSessionDataDelegate 的时候</p>    <p>会走 - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler 这么一个代理回调</p>    <p>在 challenge 这个参数里有一个 protectionSpace (受保护空间)这么一个属性,我们先打印一下看看有什么</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/70161c7e2ed8074b05ea4414dcef50b2.png"></p>    <p>打印内容</p>    <p>可以看到有 主机名, 服务器请求方法, 认证方案, 端口443,代理,代理类型等 内容. 我们可以看到认证方案为 NSURLAuthenticationMethodServerTrust</p>    <p>当认证方案为 NSURLAuthenticationMethodServerTrust 这个时, 我们需要调用completionHandler这个block, 并传递两个参数</p>    <ul>     <li>NSURLSessionAuthChallengeDisposition 是一个枚举, 告诉我们如何处理数字证书</li>    </ul>    <pre>  <code class="language-objectivec">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. */  }</code></pre>    <p>我们选择第一个,使用证书</p>    <ul>     <li>NSURLCredential * _Nullable 这个参数我们需要传一个证书进去,如何拿到这个证书对象呢? 我们使用这个方法</li>    </ul>    <pre>  <code class="language-objectivec">NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];</code></pre>    <p>我们拿到这两个参数之后, 调用block,这样就完整地发送了一个HTTPS请求</p>    <pre>  <code class="language-objectivec">- (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);    }</code></pre>    <p>运行结果如下</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/0d3f78c98a89247522f1292fcf6fc169.png"></p>    <p>打印出了网页内容</p>    <ul>     <li>使用AFN框架发送HTTPS请求</li>    </ul>    <pre>  <code class="language-objectivec">- (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);          }      }];  }</code></pre>    <p>其他的都跟HTTP请求一样, 只是需要设置三个属性</p>    <ul>     <li> <p>manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 因为接收到的是html数据, 需要用原始解析,而不是默认的JSON解析</p> </li>     <li> <p>manager.securityPolicy.allowInvalidCertificates = YES; 因为12306网站采用的是自认证, 所以我们需要允许无效证书, 默认是NO</p> </li>     <li> <p>manager.securityPolicy.validatesDomainName = NO; 使域名有效,我们需要改成NO,默认是YES</p> </li>    </ul>    <p>这三个属性设置完毕之后, 就可以成功地发送HTTPS请求了.</p>    <p>运行结果:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/2d2e9cd6eff4e3a4bc65d60bbb89c17b.png"></p>    <p>运行结果</p>    <p> </p>    <p>来自:http://www.jianshu.com/p/d833ac6fa5ab</p>    <p> </p>