繁体   English   中英

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

[英]Java GDAX Authenticated REST Request HTTP GET Error 400

我正在尝试使用经过身份验证的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;


}

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;   
}

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

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

创建签名

创建标题

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

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

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

希望,这可能会有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM