我在为 GDAX API 签名消息时遇到问题。GDAX API 文档指出状态 400 ~ “Bad Request – Invalid request format”。你能告诉我我需要改变什么吗?
谢谢!
protected Void doInBackground(String... params) {
try {
URL url = new URL(baseUrl+params[0]);
// Create the urlConnection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("CB-ACCESS-KEY", key);
urlConnection.setRequestProperty("CB-ACCESS-SIGN", generate(params[0], "GET", "", String
.valueOf(System.currentTimeMillis())));
String timestamp = String.valueOf(System.currentTimeMillis());
urlConnection.setRequestProperty("CB-ACCESS-TIMESTAMP", timestamp);
urlConnection.setRequestProperty("CB-ACCESS-PASSPHRASE", passphrase);
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
String response = convertInputStreamToString(inputStream);
Log.d("TAG", String.valueOf(response));
} else {
Log.d("TAG", String.valueOf(statusCode));
}
} catch (Exception e) {
Log.d("TAG", e.getLocalizedMessage());
}
return null;
}
生成 CB-ACCESS-SIGN
public String generate(String requestPath, String method, String body, String timestamp) {
try {
String prehash = timestamp + method.toUpperCase() + requestPath + body;
byte[] secretDecoded = Base64.decode(secretKey, Base64.DEFAULT);
SecretKeySpec keyspec = new SecretKeySpec(secretDecoded, "HmacSHA256");
Mac sha256 = GDAXConstants.SHARED_MAC;
sha256.init(keyspec);
String shadone = Base64.encodeToString(sha256.doFinal(prehash.getBytes()),Base64.DEFAULT);
return shadone;
} catch (InvalidKeyException e) {
e.printStackTrace();
throw new RuntimeException(new Error("Cannot set up authentication headers."));
}
}