如何在 Rest-Assured java 中使用证书进行 HTTPS GET 调用

2022-01-25 00:00:00 certificate java rest-assured

如何在 java 中使用 Rest-Assured 对需要证书的端点进行 GET 调用.我有 .pem 格式的证书.在 PEM 文件中有证书和私钥.

How can I make a GET call using Rest-Assured in java to a endpoint which requires certificate. I have certificate as .pem format. In PEM file there is certificate and private key.

推荐答案

用下面的代码搞定 -

KeyStore keyStore = null;
SSLConfig config = null;

try {
        keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(
                new FileInputStream("certs/client_cert_and_private.p12"),
                password.toCharArray());

    } catch (Exception ex) {
        System.out.println("Error while loading keystore >>>>>>>>>");
        ex.printStackTrace();
    }

    if (keyStore != null) {

        org.apache.http.conn.ssl.SSLSocketFactory clientAuthFactory = new org.apache.http.conn.ssl.SSLSocketFactory(keyStore, password);

        // set the config in rest assured
        config = new SSLConfig().with().sslSocketFactory(clientAuthFactory).and().allowAllHostnames();

RestAssured.config = RestAssured.config().sslConfig(config);
RestAssured.given().when().get("/path").then();

相关文章