Scala: How to ignore 'SSLHandshakeException'

后端 未结 1 1526
北海茫月
北海茫月 2021-02-09 01:26

With such code:

val html = Source.fromURL(\"https://scans.io/json\")

Getting exception:

Exception in thread \"main\" javax.net.         


        
相关标签:
1条回答
  • 2021-02-09 02:03

    You can achieve this by configuring a SSLContext.

    Here is a working code

    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
    
      def checkClientTrusted(x509Certificates: Array[X509Certificate], s: String) = {}
    
      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)
    }
    

    How it works

    Source.fromURL uses java.net.HttpURLConnection behind the scene. So this code simply works because TrustAll bypasses checkClientTrusted and checkServerTrusted methods.

    0 讨论(0)
提交回复
热议问题