簡體   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