如何在Java中通过HTTP请求传递Api Key?

huangapple go评论72阅读模式
英文:

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

问题

我一直在尝试使用以下示例的请求头通过 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 请求的标头吗?

英文:

i been trying to access an api with the request header example below using java

curl -X GET -k --header "x-apikey: accesskey=4def6bc216f14c1ab86dfba8738ff4a5; secretkey=a47d1d3a071443449a75821129526b96" https://Tenable.sc/rest/currentUser***`***

like so

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());

May i know how to convert the curl request example above into a header for a http request?

答案1

得分: 2

你现在有的部分看起来不错。为了模拟 -k 标志,该标志会关闭主机名验证,您需要进行另一个调用:

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

没有这个,您可能会看到证书错误。

英文:

What you have looks good. To simulate the -k flag, which turns off hostname verification, you'll need to make another call:

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

Without that, you'll might see certificate errors.

huangapple
  • 本文由 发表于 2020年10月7日 11:34:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/64236807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定