我正在尝试访问可在 https 协议上使用的 Web 服务。最初我收到以下错误:
NSURLSession/NSURLConnection HTTP 加载失败 (kCFStreamErrorDomainSSL, -9802) 错误发生 SSL 错误,无法与服务器建立安全连接。
我通过在 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 委托方法中得到以下响应:
<!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
我已经从 info.plist 中删除了通过 http 的密钥,因为该服务已经是 https
更新 3
当我尝试使用 openssl 作为
openssl s_client -showcerts -connect xx.xx.xxx.xxx:443
但我收到以下错误:
CONNECTED(00000003) 8012:error:140790E5:SSL 例程:SSL23_WRITE:ssl 握手失败:/SourceCache/OpenSSL098/OpenSSL098-52.40.1/src/ssl/s23_lib.c:185
Update4: 将 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) 错误发生 SSL 错误,无法与服务器建立安全连接。