gpt4 book ai didi

Scala:如何忽略 'SSLHandshakeException'

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:17 24 4
gpt4 key购买 nike

使用这样的代码:

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 中修复它?

最佳答案

您可以通过配置 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 绕过了 checkClientTrustedcheckServerTrusted 方法。

关于Scala:如何忽略 'SSLHandshakeException',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28785609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com