通过Java执行curl

时间:2018-08-28 19:11:41

标签: java curl httpurlconnection

我有一个有效的curl命令:

curl -X POST http://localhost:8086/write?db=mydb --data-binary 'temp,device=xyz value=33'

我想通过Java执行它。

String url = "http://localhost:8086/write?db=mydb";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("POST");

如何在Java代码中定义“ --data-binary”参数。

1 个答案:

答案 0 :(得分:0)

运行示例代码:

HttpURLConnection conn = (HttpURLConnection) (new URL("https://www.quora.com")).openConnection();

conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);

conn.setRequestMethod("PUT");
JSONObject data = new JSONObject();
//Now add all the data to this object using accumulate.

OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);

Bufferedreader reader = new BufferedReader ( new InputStreamReader(conn.getInputStream());
for (String line; (line = reader.readLine()) != null;) {
        System.out.println(line);
}
reader.close();
out.close();

OR

Process p = Runtime.getRuntime().exec("diff fileA fileB"); //put curl instead of diff                                                                                                                                                    
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
}