我正在尝试访问一个使用https协议的Web服务。最初我遇到了以下错误:
NSURLSession/NSURLConnection HTTP加载失败(kCFStreamErrorDomainSSL,-9802) errorAn SSL error has occurred and a secure connection to the server cannot be made.
我通过在我的info.plist文件中添加以下内容来解决问题:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>xx.xx.xxx.xxx</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
但现在在connectionDidFinishLoading代理方法中,我得到了以下作为HTML的响应:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
</body>
</html>
我正在使用以下内容来建立与服务器的信任关系:
func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool{
return true
}
func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge){
print("willSendRequestForAuthenticationChallenge")
let protectionSpace:NSURLProtectionSpace = challenge.protectionSpace
let sender: NSURLAuthenticationChallengeSender? = challenge.sender
if(protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust){
let trust:SecTrustRef = challenge.protectionSpace.serverTrust!
let credential:NSURLCredential = NSURLCredential.init(forTrust: trust)
sender?.useCredential(credential, forAuthenticationChallenge: challenge)
}
else{
sender?.performDefaultHandlingForAuthenticationChallenge!(challenge)
}
}
更新1
服务器日志显示以下错误:
提供的SNI主机名xx.xx.xxx.xx与通过HTTP提供的主机名my_secured_host_name不同
如何在SNI中添加主机名?
更新2
由于服务已经是https,我已从info.plist中删除了绕过http的关键字。
更新3
当我尝试使用openssl执行以下命令:
openssl s_client -showcerts -connect xx.xx.xxx.xxx:443
但是我得到以下错误:
CONNECTED(00000003) 8012:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:/SourceCache/OpenSSL098/OpenSSL098-52.40.1/src/ssl/s23_lib.c:185
更新4: 已更改Info.plist如下:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>xx.xx.xxx.xxx</key>
<dict>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
仍然出现以下错误:
NSURLSession/NSURLConnection HTTP加载失败(kCFStreamErrorDomainSSL,-9802) error 发生了SSL错误,无法建立到服务器的安全连接。