我正在打开 SSL 连接以在 Swift 中检索 JSON,但正在使用自签名证书对我自己的服务器进行测试。以下是 URL 请求的片段:
var urlPath = "https://myhost.com/get_json"
var url: NSURL = NSURL(string: urlPath)
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
connection.start()
但是,由于证书的原因,它被(正确地)拒绝:
Opening connection to https://myhost.com/get_json
2014-06-05 09:37:02.543 AppName[44835:3182593] NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
Connection failed.The certificate for this server is invalid. You might be connecting to a server that is pretending to be “myhost.com” which could put your confidential information at risk.## Heading ##
您将需要这些附加方法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
{
if challenge?.protectionSpace.host == "www.myhost.com"
{
let credentials = NSURLCredential(forTrust: challenge!.protectionSpace.serverTrust)
challenge!.sender.useCredential(credentials, forAuthenticationChallenge: challenge)
}
}
challenge?.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)
}
NOTE:这仅在使用异步时才可能NSURLConnection
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)