java - JAVA调用API成功但邮递员失败
问题描述
我有一个调用 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;
}
}
邮递员输入:
解决方案
在通过剪贴板将 sysout 控制台中的数据复制粘贴到 PostMan 时,这看起来像是一些编码问题。当您执行 system.out.println 时,如果源字符串编码和 sysout 控制台识别的编码不同,您可能无法获得正确的值。
推荐阅读
- angular - 最佳实践:如何将 Angular 接口和 WebAPI 类保持在一起
- unity3d - 在编辑器中创建多个材质与在运行时创建多个材质
- android - 在 Android Studio 中单击“运行测试”时会执行什么?
- docker - 使用 AspNetCore Api 设置 NLog 并使用 Docker 进行调试会持续抛出找不到文件错误
- vue.js - 如何实现我自己的上传文件组件并在vue js中进行自定义?
- php - 当我提供正确的密码时,为什么我的密码哈希返回错误?
- node.js - 无法在nodejs中绑定参数
- c++ - 在 CreateInstance 函数执行期间访问冲突
- c# - 如何使用 C# 在 Unity 中截取我的桌面应用程序的当前视图?
- google-cloud-platform - 无法从文件中读取 GCS 凭据