SSLHandshakeExceptionの対応例

HttpsURLConnection con = (HttpsURLConnection)Url.openConnection();

のようにHttpsURLConnectionを用いて接続するとき、証明書エラーが生じるとSSLHandshakeExceptionという例外が発生します。

このときそのまま接続を行いたいのであれば証明書を無視した接続を行います。

以下のコードが証明書を無視した接続例です。

private static HttpURLConnection getHttpsConnection(String url) throws Exception {

    HttpURLConnection urlconn = null;
    URL connectURL = new URL(url);

    if ("https".equals(connectURL.getProtocol())) {
      TrustManager[] tm = { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
          return null;
        }
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        }
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        }
      } };
      SSLContext sslcontext = SSLContext.getInstance("SSL");
      sslcontext.init(null, tm, null);
      HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
          return true;
        }
      });

      urlconn = (HttpsURLConnection) connectURL.openConnection();
      ((HttpsURLConnection) urlconn).setSSLSocketFactory(sslcontext
        .getSocketFactory());
    } else {
      urlconn = (HttpURLConnection) connectURL.openConnection();
    }

    urlconn.setRequestMethod("GET");
    urlconn.connect();

    return urlconn;
  }


参考:http://symfoware.blog68.fc2.com/blog-entry-1165.html