繁体   English   中英

如何向 HttpsUrlConnection 指示它应该使用的证书(以前导入到 cacert 文件)

[英]How to indicate to HttpsUrlConnection the cert (previously imported to cacert file) that it should use

我正在尝试使用 web 服务,其中我们将证书导入到 JDK 的 cacert 文件中。 但我不明白如何“设置” HttpsURLConnection object 必须使用它才能执行 web 服务的证书。

我读到,一旦证书安装在 cacert 文件中,连接到 web 服务时就不再需要指示任何内容。

我目前正在跳过KeyStoreTrustStore验证来调用 web 服务。

这是我的代码:

public void tokenFotoCteNOCHOProd(String url) throws IOException {
    HttpsURLConnection conn = null;
    String params = "";
    String res = "";
    try {
        TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
                    /**/
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
                    /**/
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }
        };
            
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

        params = "someParams";
        URL url = new URL(url);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setConnectTimeout(3000);
        try (OutputStream os = conn.getOutputStream()) {
            os.write(params.getBytes(StandardCharsets.UTF_8));
            os.flush();
            res = getRespWS(conn);//get resp..
        }
    } catch (KeyManagementException | NoSuchAlgorithmException | ClassCastException | JsonParseException e) {
        LOGGER.info("error", e);
    }
}
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2023 STACKOOM.COM