【问题标题】:How to pass an Api Key in a http request with java?如何使用 java 在 http 请求中传递 Api Key?
【发布时间】:2020-10-07 03:34:55
【问题描述】:

我一直在尝试使用 java 访问带有以下请求标头示例的 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 请求示例转换为 http 请求的标头吗?

【问题讨论】:

    标签: java api curl http-headers httprequest


    【解决方案1】:

    你的东西看起来不错。要模拟关闭主机名验证的 -k 标志,您需要再次调用:

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

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

    【讨论】:

    • hmmm 我一直收到 403(禁止)的响应代码,我很确定我的 api 密钥是有效的。难道是我没有正确创建http请求?
    • nvm,它正在工作。我的代码一直都是正确的。谢谢 schtever
    猜你喜欢
    • 1970-01-01
    • 2018-05-30
    • 2020-07-30
    • 2021-02-16
    • 2013-07-07
    • 2014-08-13
    • 2014-12-20
    • 1970-01-01
    • 2012-02-16
    相关资源
    最近更新 更多