首页 > 系统 > iOS > 正文

ios 配置HTTPS (单向验证,工程不需要加证书)

2019-11-08 00:34:03
字体:
来源:转载
供稿:网友

这个问题坑了我两天啊!网上各种搜,也没解决了。

后台单向验证,自签名证书!

客户端需要做的事情:

一、swift   Alamofire网络请求

在请求方法前面加上以下代码即可:
let manager: Alamofire.Manager = {            let manager = Alamofire.Manager.sharedInstance            manager.delegate.sessionDidReceiveChallenge = { session, challenge in                var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling                var credential: NSURLCredential?                                if challenge.PRotectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {                    disposition = NSURLSessionAuthChallengeDisposition.UseCredential                    credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)                } else {                    if challenge.previousFailureCount > 0 {                        disposition = .CancelAuthenticationChallenge                    } else {                        credential = manager.session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)                                                if credential != nil {                            disposition = .UseCredential                        }                    }                }                return (disposition, credential)            }            return manager        }()

二、 UIWebView 配置https(因为我的工程全是swift写的,贴上swift代码,oc自己转吧!)

主要实现NSURLConnectionDelegate两个代理方法:

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool {        return (protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust)    }    func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {        if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {            challenge.sender!.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)            challenge.sender!.continueWithoutCredentialForAuthenticationChallenge(challenge)        }            }这样就搞定了 ,坑了我两天啊,swift的更是不好找!

本人菜鸟,哪不对欢迎提出


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表