JAVA 调用 API 成功但 Postman 失败

时间:2021-06-29 08:55:29

标签: java api postman

我有一个调用 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;
     }
}

邮递员输入:

headers in Postman

body in Postman

2 个答案:

答案 0 :(得分:0)

一些可能性是:

  • 您在 Postman 中粘贴的签名中有一些额外的空格或新行
  • 每个签名只被接受一次,所以如果你从 Java 代码中使用它,你就不能从 Postman 中再次使用相同的签名

答案 1 :(得分:0)

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

相关问题