Java GDAX经过身份验证的REST请求HTTP GET错误400

时间:2017-12-05 20:33:46

标签: java json rest get http-headers

我正在尝试使用经过身份验证的API请求从GDAX Exchange获取数据。我从一个简单的账户余额检查开始。

我一直在调整我的代码大约8个小时,除了400响应之外似乎无法得到任何东西。谁能帮我理解我做错了什么?

https://docs.gdax.com/#authentication

  

所有REST请求必须包含以下标头:

     
      
  • CB-ACCESS-KEY api键为字符串。
  •   
  • CB-ACCESS-SIGN base64编码的签名(请参阅签名消息)。
  •   
  • CB-ACCESS-TIMESTAMP您的请求的时间戳。
  •   
  • CB-ACCESS-PASSPHRASE您在创建API密钥时指定的密码。
  •   
     

所有请求正文都应该包含内容类型application / json   有效的JSON。

  

通过使用创建sha256 HMAC生成CB-ACCESS-SIGN标头   preshsh字符串时间戳+方法上的base64解码密钥   + requestPath + body(其中+表示字符串连接)和base64编码输出。时间戳值与。相同   CB-ACCESS-TIMESTAMP标题。

     

如果没有请求,正文是请求正文字符串或省略   正文(通常用于GET请求)。

     

该方法应为大写。

private static JSONObject getAuthenticatedData() {
    try {

        String accessSign = getAccess();


        URL url = new URL("https://api.gdax.com/accounts");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");

        con.setRequestProperty("CB-ACCESS-KEY", "d281dc......");
        con.setRequestProperty("CB-ACCESS-SIGN", accessSign);
        con.setRequestProperty("CB-ACCESS-TIMESTAMP", ""+System.currentTimeMillis() / 1000L);
        con.setRequestProperty("CB-ACCESS-PASSPHRASE", "xxxxx.....");

        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);

        int status = con.getResponseCode();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        System.out.println(content);
        in.close();

        con.disconnect();

    }catch(Exception e) {
        e.printStackTrace();
    }
    return null;


}

public static String getAccess() {

    //Set the Secret
    String secret = "xxxxxxx........";
    //Build the PreHash
    String prehash = Instant.now().toEpochMilli()+"GET"+"/accounts";
    String hash = null;
    try {

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        hash = Base64.encodeBase64String(sha256_HMAC.doFinal(prehash.getBytes()));
        System.out.println(hash);
       }
       catch (Exception e){
           e.printStackTrace();
       }
    return hash;   
}

2 个答案:

答案 0 :(得分:3)

您需要添加请求标头和请求属性。

以下是您正在尝试做的事情的示例:

Create Signature

Create Headers

答案 1 :(得分:0)

A 400表示请求格式错误。换句话说,客户端发送到服务器的数据流不遵守规则。

所以,你身边出了点问题。在官方文档中提到您应该请求POST方法但是您有请求GET方法。

 URL url = new URL("https://api.gdax.com/accounts");
 HttpURLConnection con = (HttpURLConnection) url.openConnection();
 con.setRequestMethod("POST");

希望,这可能有所帮助!

相关问题