【发布时间】:2021-09-11 11:27:52
【问题描述】:
我有一个调用 API 的 JAVA 程序。 API 需要正文加密并使用 Hmac256 对标头 + 正文进行签名。下面的源代码返回期望的结果。但是,如果我“System.out.print”标头和正文并将其直接从 Java 复制到 Postman 以发出请求,API 在 Postman 中返回“签名验证失败”。有人知道我错过了什么吗?
我在下面包含了代码和邮递员输入。谢谢。
public class HelloWorld{
public static void main(String []args){
System.setProperty("java.net.useSystemProxies", "true");
HttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build();
// header
long now = System.currentTimeMillis();
HttpPost httpPost = new HttpPost("https://example/api/v1");
String timestamp = String.valueOf(now);
String nonce = getRandomStringByLength(32);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("clientID", clientID);
httpPost.setHeader("timestamp", timestamp);
httpPost.setHeader("nonce", nonce);
// body
JSONObject contentJson = new JSONObject();
contentJson.put("businessID", getRandomStringByLength(36));
String[] info = new String[] {"name", "phone", "email"};
contentJson.put("Fields", info);
// encrypting the body
JSONObject bodyJson = new JSONObject();
bodyJson.put("content", encrypt(key,contentJson.toString()));
String body = bodyJson.toString();
// creating a signature
String signature = signData(secret,clientID + timestamp + nonce + body);
httpPost.setHeader("signature", signature);
try {
StringEntity requestEntity = new StringEntity(body);
httpPost.setEntity(requestEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(httpResponse.getEntity());
System.out.println(result);
return result;
}
String responseString = new BasicResponseHandler().handleResponse(httpResponse);
} catch (Exception e) {
System.out.println(e);
return null;
}
return null;
}
}
邮递员输入:
【问题讨论】: