如何使用 java 在 http 请求中传递 Api 键?

How to pass an Api Key in a http request with java?

我一直在尝试使用 java

通过下面的请求 header 示例访问 api
curl -X GET -k --header "x-apikey: accesskey=4def6bc216f14c1ab86dfba8738ff4a5; secretkey=a47d1d3a071443449a75821129526b96" https://Tenable.sc/rest/currentUser***`***

像这样

URL urlcon= new URL("https://Tenable.sc/rest/currentUser");
HttpsURLConnection connection = (HttpsURLConnection) urlcon.openConnection();
connection.setRequestMethod("GET");

String apiKey = "accesskey:4def6bc216f14c1ab86dfba8738ff4a5; secretkey:a47d1d3a071443449a75821129526b96;";

connection.setRequestProperty("x-apikey", apiKey);

System.out.println(connection.getResponseCode());

我可以知道如何将上面的 curl 请求示例转换为 header 的 http 请求吗?

你的看起来不错。要模拟关闭主机名验证的 -k 标志,您需要进行另一个调用:

connection.setHostnameVerifier(new HostnameVerifier() {
    boolean verify(String hostname, SSLSession session) {
        return true;
    }
});

否则,您可能会看到证书错误。