GDAX Лимитный ордер Java (HTTP Post)

Попытка отправить запрос HTTP Post в GDAX с авторизацией. Запросы «GET» работают нормально, и я не уверен, правильно ли я передаю параметры json, поскольку продолжаю получать неверный запрос.

private static JsonObject LimitOrder(String symbol, boolean side, String quantity, String price)
    {
        BigDecimal dPrice = new BigDecimal(price);
        BigDecimal dQuantity = new BigDecimal(quantity);
        String sSide = side?"buy":"sell";
        String param  ="{\"size\":\""+dQuantity.toString()+"\",\"price\":\""+dPrice.toString()+"\",\"side\":\""+sSide+"\",\"product_id\":\""+symbol+"\",\"post_only\":true}";


        try
        {
                String timestamp= Instant.now().getEpochSecond()+"";
                String accessSign = getAccess(timestamp,"POST","/orders");
                String apiKey = properties.getProperty("key");
                String passphrase = properties.getProperty("passphrase");

                URL url = new URL("https://" + properties.getProperty("host") + "/orders");
                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                connection.setDoOutput(true); // Triggers POST.
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                connection.setRequestProperty("CB-ACCESS-KEY", apiKey);
                connection.setRequestProperty("CB-ACCESS-SIGN", accessSign);
                connection.setRequestProperty("CB-ACCESS-PASSPHRASE", passphrase);
                connection.setRequestProperty("CB-ACCESS-TIMESTAMP", timestamp);
                connection.setRequestProperty("accept", "application/json");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);

        //      System.out.println("WRiting: " + param);
              try (OutputStream output = connection.getOutputStream()) {
                output.write(param.getBytes("UTF-8"));
              }

              String status = connection.getResponseMessage();
                System.out.println("STATUS: "+status);

                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer content = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                if(content.length()>0){
                System.out.println(content);
                }else{
                     System.out.println("Empty Response");

                }
                in.close();

                connection.disconnect();
            }catch(Exception e) {
                e.printStackTrace();
            }
        return null;
    }

и метод знака доступа ниже:

 private static String getAccess(String timestamp, String method, String path) throws NoSuchAlgorithmException, InvalidKeyException {
        String secret = properties.getProperty("secret");
        String prehash = timestamp+method+path;

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        byte[] secretDecoded = Base64.getDecoder().decode(secret);
        SecretKeySpec secret_key = new SecretKeySpec(secretDecoded, "HmacSHA256");
        sha256_HMAC.init(secret_key);

        return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(prehash.getBytes()));
    }

Ответы (1)

Ваша строка JSON выглядит нормально, однако я предлагаю вам использовать класс библиотеки JSONObject .

В вашем методе getAccess(), я думаю, вам не хватает переменной param .

   Предварительный хэш строки = метка времени + метод + путь + параметр;