Swift:如何使用自签名证书请求URL? [英] Swift: How to request a URL with a self-signed certificate?

查看:387
本文介绍了Swift:如何使用自签名证书请求URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在打开SSL连接以在Swift中检索JSON,但正在使用自签名证书针对我自己的服务器进行测试.这是URL请求的一个片段:

I'm opening an SSL connection to retrieve JSON in Swift, but am testing against my own server with a self-signed certificate. Here's a snippet of the URL request:

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()

但是,由于证书的原因,它被拒绝(正确):

However, it gets rejected (correctly) because of the certificate:

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中的这些其他方法:

You will need these additional methods from 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)
}

注意::仅当使用异步NSURLConnection时才可能.

NOTE: This is only possible when using the asynchronous NSURLConnection.

这篇关于Swift:如何使用自签名证书请求URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆