我正在尝试使用RestTemplate将订单过帐到币安。下一个简化代码:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("user-agent",
"Mozilla/5.0 " +
"(Windows NT 10.0; Win64; x64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/54.0.2840.99 " +
"Safari/537.36");
headers.add(X_MBX_APIKEY, apiKey);
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
long time = new Date().getTime();
String params1 = "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.005&recvWindow=50000" +
"×tamp=" + time;
String signature = encodeSHA256(secretKey, params1);
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("https://api.binance.com/api/v3/order/test")
.queryParam("symbol", "LTCBTC")
.queryParam("side", "BUY")
.queryParam("type", "LIMIT")
.queryParam("timeInForce", "GTC")
.queryParam("quantity", "1")
.queryParam("price", "0.005")
.queryParam("recvWindow", "50000")
.queryParam("timestamp", time)
.queryParam("signature", signature);
ResponseEntity<String> response = restTemplate.exchange(builder.build().toUri(), HttpMethod.POST, entity, String.class);
所以我得到下一个异常:
org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: [{"code":-1104,"msg":"Not all sent parameters were read; read '9' parameter(s) but was sent '10'."}]
at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:101)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:170)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:112)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:782)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:740)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:714)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:602)
邮递员中的相同请求效果很好。那么这个错误的原因是什么呢?因为请求中的参数数量为9。也许binance api将标头中的apiKey识别为第十个参数?预先谢谢你。
答案 0 :(得分:0)
我不知道为什么restTemplate不起作用,但是我从使用okhttp3的邮递员那里复制了代码。现在就可以了。
long time = new Date().getTime();
String params = "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1" +
"&price=0.004&recvWindow=50000" +
"×tamp=" + time;
String signature = encodeSHA256(marketKey, params);
Request request = new Request.Builder()
.url("https://api.binance.com/api/v3/order" +
"?symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1" +
"&price=0.004&recvWindow=50000" +
"×tamp=" + time +
"&signature=" + signature)
.post(new RequestBody() {
@Nullable
@Override
public MediaType contentType() {
return null;
}
@Override
public void writeTo(BufferedSink bufferedSink) throws IOException {
}
})
.addHeader("X-MBX-APIKEY", apiKey)
.build();