Java GDAX认证REST请求HTTP GET错误400

5

我正在尝试使用身份验证的API请求从GDAX交易所获取数据。我从账户余额查询开始。

我已经调整了代码大约8个小时,但似乎除了400响应之外什么都没有得到。有谁能帮我理解我做错了什么吗?

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

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

  • CB-ACCESS-KEY作为字符串的API密钥。
  • CB-ACCESS-SIGN 经过base64编码的签名(请参阅Signing a Message)。
  • CB-ACCESS-TIMESTAMP 您的请求的时间戳。
  • CB-ACCESS-PASSPHRASE 创建API密钥时指定的密码。

所有请求正文应该具有内容类型application/json并且是有效的JSON。

~

通过使用base64解码的密钥在预哈希字符串timestamp + method + requestPath + body上创建sha256 HMAC生成CB-ACCESS-SIGN头文件(其中+表示字符串连接),并对输出进行base64编码。时间戳值与CB-ACCESS-TIMESTAMP标头相同。

body是请求正文字符串,如果没有请求正文(通常针对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个回答

3

1
嗨@Shawn,你能否在这里发布代码而不是链接?链接可能会在未来更改。 - Nathaniel Flick
这里给出的代码使用了Spring进行REST请求。如何在“纯”Java中实现这一功能? - Ben

0

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

因此,问题出在您这边。官方文档中提到您应该使用 POST 方法进行请求,但您却使用了 GET 方法。

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

希望这有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接