Scala:如何忽略“SSLHandshakeException" [英] Scala: How to ignore 'SSLHandshakeException'
本文介绍了Scala:如何忽略“SSLHandshakeException"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用这样的代码:
val html = Source.fromURL("https://scans.io/json")
获取异常:
Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1886)
...
我可以在 Java 中找到如何修复但不知道 - 如何在 Scala 中修复它?
I can find how to fix in Java but have no idea - how to fix it in Scala?
推荐答案
您可以通过配置 SSLContext
来实现这一点.
You can achieve this by configuring a SSLContext
.
这是一个工作代码
import javax.net.ssl._
import java.security.cert.X509Certificate
import scala.io.Source
// Bypasses both client and server validation.
object TrustAll extends X509TrustManager {
val getAcceptedIssuers = null
override def checkClientTrusted(x509Certificates: Array[X509Certificate], s: String) = {}
override def checkServerTrusted(x509Certificates: Array[X509Certificate], s: String) = {}
}
// Verifies all host names by simply returning true.
object VerifiesAllHostNames extends HostnameVerifier {
def verify(s: String, sslSession: SSLSession) = true
}
// Main class
object Test extends App {
// SSL Context initialization and configuration
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, Array(TrustAll), new java.security.SecureRandom())
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory)
HttpsURLConnection.setDefaultHostnameVerifier(VerifiesAllHostNames)
// Actual call
val html = Source.fromURL("https://scans.io/json")
println(html.mkString)
}
工作原理
Source.fromURL
在幕后使用 java.net.HttpURLConnection
.所以这段代码很简单,因为 TrustAll
绕过了 checkClientTrusted
和 checkServerTrusted
方法.
How it works
Source.fromURL
uses java.net.HttpURLConnection
behind the scene. So this code simply works because TrustAll
bypasses checkClientTrusted
and checkServerTrusted
methods.
这篇关于Scala:如何忽略“SSLHandshakeException"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文