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

use*_*872 5 java rest json 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.

CB-ACCESS-SIGN标头是通过在prehash字符串时间戳+ method + requestPath + body(其中+表示字符串连接)上使用base64解码的密钥创建sha256 HMAC并对输出进行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;


}
Run Code Online (Sandbox Code Playgroud)

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;   
}
Run Code Online (Sandbox Code Playgroud)

小智 3

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

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

创建签名

创建标题