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

标签 java android ssl httpurlconnection

<分区>

当我想打开一个 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, 0, 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;
    }

关于java - 禁用 HTTPS 连接的 SSL 证书验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12170396/

相关文章:

java - 从文件中读取 Shorts 和字符

java - 捕获无效输入的 IOException

android - 如何使用 GitHub 上的 OpenStreetMap 库

使用 fragment 的 Android 功能区菜单

.jar 中的 Java 调用函数

java - Java 中键值对的有序集合

java - 接受不受信任的 SSL 证书 FireFox Selenium RemoteWebDriver

docker - 为什么我无法通过 HTTPS 访问我的 traefik 仪表板?

java - 一次从数据库中获取所有问题还是一次获取一个问题?

c++ - SSL_accept 需要 200 毫秒 (c/openssl)