【问题标题】:"cURL -u" API Key Authorization with Apache HTTPClient使用 Apache HTTPClient 的“cURL -u”API 密钥授权
【发布时间】:2017-10-06 22:01:36
【问题描述】:

我可以使用REST API 使用cURL 就像在this 答案中一样。现在我想使用Apache Commons HTTPComponents 库将其“翻译”为Java 代码。我只是在添加API key 授权标头时遇到问题:

HttpPost request = new HttpPost(DE_COMPILATION_URL);
byte[] encodedAuth = Base64.encodeBase64(API_KEY.getBytes(StandardCharsets.UTF_8));
String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
request.setHeader("mode", "raw");
request.setHeader("input", "@" + machineCodeFile.toString() + ";filename=" + machineCodeFile.getName());
request.setHeader("architecture", "powerpc");
request.setHeader("endian", "big");
request.setHeader("raw_entry_point", "0x0");
request.setHeader("raw_section_vma", "0x0");
request.setHeader("target_language", "c");

HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);

打印出来:

{
    "code": 401,
    "description": "API key authorization failed (missing or invalid API key).",
    "message": "Unauthorized by API Key"
}

我尝试了不同的授权代码,但都没有奏效。可能是什么问题呢? API 密钥正确且适用于cURL

【问题讨论】:

    标签: java http-post authorization apache-httpclient-4.x


    【解决方案1】:

    没关系,我忘了最后一个冒号。必须包含在base64 编码中:

    HttpPost request = new HttpPost(DE_COMPILATION_URL);
    byte[] encodedAuth = Base64.encodeBase64((API_KEY + ":").getBytes(StandardCharsets.UTF_8));
    String authHeader = "Basic " + new String(encodedAuth);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 2020-08-17
      相关资源
      最近更新 更多