0

我想发表一篇关于苹果新发布者 API 的文章。我正在尝试复制相同的 python 代码以在苹果文档中创建一篇文章

String body = new ObjectMapper().writeValueAsString(articleModel); //a json model that represents the article
String finalUrl = baseURL + channelId + "/articles/";
String date= getCurrentDate();
String canonical_request = "POST"+finalUrl + date + "multipart/form-data; boundary=1906ef19a2044180b914d742c37e2ace"+ body;
String authHeader = "HHMAC; key="+apiKeyId+";signature="+getSignature(secret, canonical_request)+";date="+date;


  CloseableHttpClient client = HttpClients.createDefault();
  HttpPost httpPost = new HttpPost(finalUrl);

  StringEntity entity = new StringEntity(new ObjectMapper().writeValueAsString(body));
  httpPost.setEntity(entity);

  httpPost.setHeader("Content-type", "'multipart/form-data; boundary=1906ef19a2044180b914d742c37e2ace'");
  httpPost.setHeader("Authorization", authHeader);

  CloseableHttpResponse response = client.execute(httpPost)

这就是我获得签名的方式:

private static String getSignature(String key, String data) {
 Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
 SecretKeySpec secret_key = new SecretKeySpec(Base64.getDecoder().decode(key), "HmacSHA256");
 sha256_HMAC.init(secret_key);
 byte [] m = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
 return Base64.getEncoder().encodeToString(m);
}

我总是收到 401:未经授权

4

1 回答 1

0

试试下面的方法:

private byte[] decodedKey = Base64.getDecoder().decode(api_key_secret);
private HmacUtils hmacUtils = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, decodedKey);

byte[] base64EncodedMac = Base64.getEncoder().encode(hmacUtils.hmac(outputStream.toByteArray()));

String signature = new String(base64EncodedMac);
String authorization = String.format("HHMAC; key=%s; signature=%s; date=%s", api_key_id, signature, date);
于 2018-11-19T16:16:27.627 回答