【发布时间】:2018-05-19 14:54:29
【问题描述】:
我正在尝试使用经过身份验证的 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 标头是通过使用创建 sha256 HMAC 生成的 prehash 字符串时间戳 + 方法上的 base64 解码密钥 + requestPath + body(其中 + 表示字符串连接)和 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;
}
【问题讨论】:
标签: java json rest get http-headers