Не удалось получить ответ от метода POST HttpURLConnection - PullRequest
0 голосов
/ 02 июня 2019

Я видел несколько потоков по этой проблеме, но, к сожалению, я не мог понять, как решить мою проблему из них. Нужна помощь, чтобы узнать, как исправить мой Java-код, так как вы можете догадаться, что мои навыки кодирования все еще ограничены.

Удалось найти решения для методов "GET" и "DELETE". Пример написан на C # и CURL, но мои навыки ограничены интерпретацией частей кода.

https://github.com/tradeio/api-csharpclient/blob/master/Tradeio.Client/TradeioApi.cs

Вот моя реализация Java:

    public String PlaceOrder(String symbol, String side, String type, String quantity, String price) throws MalformedURLException, IOException {

        LinkedHashMap<String, String> form = new LinkedHashMap<String, String>();

        form.put("Symbol", symbol);
        form.put("Side", side);
        form.put("Type", type);
        form.put("Quantity", quantity);
        form.put("Price", price);
        form.put("ts", String.valueOf(System.currentTimeMillis()));

        return signAndSend2("/order", form, "POST");
    }

        private String signAndSend2(String url, LinkedHashMap<String, String> payload, String method)
            throws MalformedURLException, IOException {

        String nonce = String.valueOf(System.currentTimeMillis());
        String baseUrl = UrlTradeio.urlV1;
        String sign = "";

        HttpURLConnection conn = null;

        JSONObject json = new JSONObject(payload);
        String formForPayload = json + "";

        StringBuilder sb = new StringBuilder();
        for (Entry<String, String> param : payload.entrySet()) {
            if (sb.length() != 0)
                sb.append('&');
            sb.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            sb.append('=');
            sb.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

        }

        byte[] postDataBytes = sb.toString().getBytes("UTF-8");
        int postDataLength = postDataBytes.length;

//      System.out.println(sb);
//      System.out.println(formForPayload);

        sign = hmac512Digest(formForPayload, TRADEIO_SECRET_KEY).toUpperCase();
        conn = (HttpURLConnection) new URL(baseUrl + url).openConnection();

        conn.setDoOutput(true);
        conn.setRequestProperty("Sign", sign);
        conn.setRequestProperty("Key", TRADEIO_API_KEY);
        conn.setRequestProperty("ts", nonce);
        conn.setRequestProperty("accept", "application/json");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        conn.setRequestMethod(method);
        conn.getOutputStream().write(postDataBytes);
        conn.connect();

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        StringBuilder output = new StringBuilder();
        for (int c; (c = in.read()) >= 0;)
            sb.append((char)c);
        String responseBody = output.toString();

        return responseBody;

    }

В зависимости от того, что я пытаюсь, у меня появляется несколько сообщений об ошибках.

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: https://api.exchange.trade.io/api/v1/order
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1913)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:245)
    at Private.TradeioApi.signAndSend2(TradeioApi.java:223)
    at Private.TradeioApi.PlaceOrder(TradeioApi.java:113)
    at test.main.main(main.java:37)```

1 Ответ

1 голос
/ 06 июня 2019

Мне удалось решить проблему.Удалено это:

conn.getOutputStream().write(postDataBytes);

И отправьте запрос так:

try(OutputStream os = conn.getOutputStream()) {
            os.write(postDataBytes);
        }
...