Https在ios客户端的objective-c实现
ios通过NSURLSession进行网络请求,参考另一篇博客ios进行网络请求。
在开发阶段,server端我们会用self-signed证书(省钱啊!)。正因为不是第三方机构认证的证书,所以客户端都会报警告。我们需要对此进行处理(参考NSURLSession in Apple Tech Note和How do I accept a self-signed SSL certificate using iOS 7’s NSURLSession and its family of delegate methods for development purposes?):
NSURLSession allows you to customize HTTPS server trust evaluation by implementing the
-URLSession:didReceiveChallenge:completionHandler:delegate method. To customize HTTPS server trust evaluation, look for a challenge whose protection space has an authentication method ofNSURLAuthenticationMethodServerTrust. For those challenges, resolve them as described below. For other challenges, the ones that you don’t care about, call the completion handler block with theNSURLSessionAuthChallengePerformDefaultHandlingdisposition and a NULL credential.When dealing with the
NSURLAuthenticationMethodServerTrustauthentication challenge, you can get the trust object from the challenge’s protection space by calling the-serverTrustmethod. After using the trust object to do your own custom HTTPS server trust evaluation, you must resolve the challenge in one of two ways:
- If you want to deny the connection, call the completion handler block with the
NSURLSessionAuthChallengeCancelAuthenticationChallengedisposition and a NULL credential.- If you want to allow the connection, create a credential from your trust object (using
+[NSURLCredential credentialForTrust:]) and call the completion handler block with that credential and theNSURLSessionAuthChallengeUseCredentialdisposition.
说了这么多,代码在下面的delegate中实现:
1 2 3 4 5 6 7 8 9 10 | |