IOS开发 支持https请求以及ssl证书配置详解

2020-01-18 20:37:36丽君

IOS开发 支持https请求以及ssl证书配置详解

前言:

众所周知,苹果有言,从2017年开始,将屏蔽http的资源,强推https

楼主正好近日将http转为https,给还没动手的朋友分享一二

一、证书准备

1、证书转换

在服务器人员,给你发送的crt证书后,进到证书路径,执行下面语句

// openssl x509 -in 你的证书.crt -out 你的证书.cer -outform der

这样你就可以得到cer类型的证书了。双击,导入电脑。

2、证书放入工程

1、可以直接把转换好的cer文件拖动到工程中。

2、可以在钥匙串内,找到你导入的证书,单击右键,导出项目,就可以导出.cer文件的证书了

二、代码准备


<key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
  </dict>

1.1 NSURLConnection设置支持https。

在2015年iOS9的更新中,NSURLConnection 被废弃 由 NSURLSession 取代,所以本身是不建议大家继续用这个类做网络请求的(同样也有AFNetWorking 2.x版本),但是考虑到一些旧程序,也不能说改就改,说替换就替换的,所以还是需要普及一下,如果用到了NSURLConnection你需要怎么做。


- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{

  if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
    // 告诉服务器,客户端信任证书
    // 创建凭据对象
    NSURLCredential *credntial = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
    // 告诉服务器信任证书
    [challenge.sender useCredential:credntial forAuthenticationChallenge:challenge];
  }
}

你只需要简单的,添加上如上的代理方法,就可以在不影响你原有请求的基础上,增加了https请求的支持了。

1.2 NSURLSession设置支持https。

现在推荐使用的就是NSURLSession来处理相关的网络请求了,如果使用系统自带的类,可以参考如下代码:


- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {

  // 判断是否是信任服务器证书
  if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
    // 告诉服务器,客户端信任证书
    // 创建凭据对象
    NSURLCredential *credntial = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
    // 通过completionHandler告诉服务器信任证书
    completionHandler(NSURLSessionAuthChallengeUseCredential,credntial);
  }
  NSLog(@"protectionSpace = %@",challenge.protectionSpace);
}