尝试发送GET请求时出现格式错误的请求异常

时间:2018-02-21 15:28:46

标签: java httpurlconnection

我正在尝试使用他们的REST API连接到GDAX

我首先想要做一些非常简单的事情,即获得historic rates

我试过了:

private static final String GDAX_URL = "https://api.gdax.com";

    public String getCandles(final String productId, final int granularity) {
        HttpsURLConnection connection = null;

        String path = "/products/" + productId + "/candles";

        try {
            //Create connection
            URL url = new URL(GDAX_URL);
            connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("granularity", String.valueOf(granularity));

            connection.setUseCaches(false);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(path);
            wr.close();

            //Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            StringBuffer response = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();

            System.out.println(response.toString());

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return null;
    }

但是我得到了400个代码作为回报“错误请求 - 无效的请求格式”。

我的问题是传递路径“/ products // candles”和参数(例如粒度)。

我不明白应该在请求属性和消息本身以及以什么形式进行什么。

1 个答案:

答案 0 :(得分:0)

我设法让它像这样工作:

URL url = new URL(GDAX_URL + path + "?granularity="+granularity);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");

不确定如何使用DataOutputStream,所以我刚删除它。至少它有效。