首页 > 解决方案 > 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;
     }
}

邮递员输入:

邮递员中的标题

邮递员的身体

标签: javaapipostman

解决方案


在通过剪贴板将 sysout 控制台中的数据复制粘贴到 PostMan 时,这看起来像是一些编码问题。当您执行 system.out.println 时,如果源字符串编码和 sysout 控制台识别的编码不同,您可能无法获得正确的值。


推荐阅读