微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 禁用HTTPS连接的SSL证书验证?

参见英文答案 > java.security.cert.CertPathValidatorException: Trust anchor for certification path not found3个
当我想打开HTTPS连接时,我得到SSL异常.如何设置HttpURLConnection以对此异常不敏感?

我的代码是:

private String getData() {
    String response = null;
    String connection = "https://www.kamalan.com/";

    try {
        URL url = new URL(connection);
        Log.i(TAG,"Try to open: " + connection);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        int responseCode = conn.getResponseCode();
        Log.i(TAG,"Response code is: " + responseCode);
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            if (in != null) {
                StringBuilder strBuilder = new StringBuilder();             
                int ch = 0;
                while ((ch = in.read()) != -1)
                    strBuilder.append((char) ch);

                // get returned message and show it
                response = strBuilder.toString();
                Log.i("JSON returned by server:",response);
            }

            in.close();

        } else {
            Log.e(TAG,"Couldn't open connection in getResepiItems()");
        }
    } catch (SSLException e) {
        e.printstacktrace();
    } catch (IOException e) {
        e.printstacktrace();
    }

    return response;
}

解决方法

按照以下方法,它适合我.
URL url = new URL("Your URL");
        HttpsURLConnection urlConnection =(HttpsURLConnection) url.openConnection();    urlConnection.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0,null));
        urlConnection.setHostnameVerifier(getHostnameVerifier());
        InputStream is = urlConnection.getInputStream();
        OutputStream os = new FileOutputStream(downloadedFile);
        byte[] data = new byte[1024];
        int count;
        while ((count = is.read(data)) != -1) {
            os.write(data,count);
        }
        os.flush();
        os.close();
        is.close();

以下方法用于设置主机名

private HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname,SSLSession session) {
                HostnameVerifier hv =
                        HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify("com.example.com",session);
            }
        };
        return hostnameVerifier;
    }

原文地址:https://www.jb51.cc/java/129026.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐