8

使用这样的代码:

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

4

1 回答 1

10

您可以通过配置一个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.fromURLjava.net.HttpURLConnection在幕后使用。所以这段代码只是因为TrustAll绕过checkClientTrustedcheckServerTrusted方法而起作用。

于 2015-02-28T22:49:45.213 回答