如何在url中使用param在java中发送这样的json post请求?

如何在url中使用param在java中发送这样的json post请求?,java,Java,我有这样的数据。我不知道如何用java编写它来发送post JSON请求。请帮帮我!我可以在Windows中使用curl实现,代码是: curl -X POST -H "Content-Type:application/json" -d "[{\"hostId\": \"01a31fc518c44166afe29a8694f4b3e8\",\"host\": \"WIN-PC_tttqa\",\"metric\": \"system.cpu.used1232\",\"timestamp\": 1

我有这样的数据。我不知道如何用java编写它来发送post JSON请求。请帮帮我!我可以在Windows中使用curl实现,代码是:

curl -X POST -H "Content-Type:application/json" -d "[{\"hostId\": \"01a31fc518c44166afe29a8694f4b3e8\",\"host\": \"WIN-PC_tttqa\",\"metric\": \"system.cpu.used1232\",\"timestamp\": 1457577649000,\"value\": 0,\"tags\": [\"location:aa\",\"level:high\"],\"type\": \"gauge\"}]" http://ip:port/openapi/v2/datapoints?api_key=fe01ce2a7fbac8fafaed7c982a04e229

您可以在“数据格式”的
img
链接中看到数据格式,请给我看一下代码,我会立即尝试

这是我的测试功能:

public void sendPost() throws JSONException {
    HttpURLConnection connection = null;

    try {
        // 创建连接
        URL url = new URL(ADD_URL);
        connection = (HttpURLConnection) url.openConnection();
        // 设置http连接属性
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");


        // 设置http头 消息
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        connection.setRequestProperty("Accept", "application/json");

        // 添加 请求内容
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        json.put("api_key", "fe01ce2a7fbac8fafaed7c982a04e229");
        json.put("hostId", "01a31fc518c44166afe29a8694f4b3e8");
        json.put("host", "WIN-PC240");
        json.put("metric", "system.cpu.used1232");
        json.put("value", 0);
        JSONArray array = new JSONArray();
        array.put("location:aaa");
        array.put("level:high");
        json.put("tags", array);
        json.put("type", "gauge");
        jsonArray.put(json);
        System.out.println(jsonArray.toString());
        OutputStream out = connection.getOutputStream();
        out.write(jsonArray.toString().getBytes());
        out.flush();
        out.close();

        // 读取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String lines;
        StringBuffer sb = new StringBuffer("");
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sb.append(lines);
        }
        reader.close();
        // // 断开连接
        connection.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我犯了一个错误。我认为post请求不能在URL中跟随“?param=…”。我只需要将“api_键”放在URL中,而不是放在JSON参数中

请告诉我代码否,请告诉我们您尝试过的代码。我显示了我的代码,我不知道如何放置api_键,这是url的参数,服务器将返回错误401