LoginSignup
5
2

More than 5 years have passed since last update.

OkHttpでサーバー証明書のないサーバーにつなげるコードを書いてみた。

Last updated at Posted at 2016-03-09

1.サーバー証明書の発行していないサーバーにhttpsでアクセスすると…

基本的に開発中の環境とかだったり、デバッグ環境とかだとサーバー証明書なんて発行してないことが多いと思います。
ところがどっこい、証明書がないところに対して「https://」使ってリクエストすると…

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException:
 Trust anchor for certification path not found.

信頼できるサーバー証明書のありかわからないから繋ぎたくないよ!
なんて感じで怒られてしまうわけです。

2.じゃあ対処法

繋ぎたくないよって言ってるだけなので、無くても強制的につながせればよいのです。

原理については検索ワード 「X509TrustManager」「HostnameVerifier」 あたりでググッてみてください。

    @deprecated("サーバー証明書を確認せずにつなぐClient生成")
  def createIgnoreCertPathValidationClient(): OkHttpClient = {

        //X.509 証明書の管理を空実装にする
    val tm: Array[TrustManager] = Array(
      new X509TrustManager {
        def getAcceptedIssuers: Array[X509Certificate] = Array.empty

        def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {}

        def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
      }
    )
    val context = SSLContext.getInstance("SSL")
    context.init(null, tm, null)

    val builder = new OkHttpClient.Builder().sslSocketFactory(context.getSocketFactory)
    builder.hostnameVerifier(new HostnameVerifier {
            //どんなホスト名でもつないじゃうぜ!
      def verify(hostname: String, session: SSLSession): Boolean = true
    })
    builder.build()
  }

危なめの関数なので、用量用法には十分気をつけて使いましょう。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2