I have such a data. I don't know how to write it in java to send a post JSON request. Please help me! I can do it with curl in Windows, the code is:
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
You can see the data format in the img
link of "data format", please show me the code, then I will try it immediately.
This is my test function:
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();
}
}