0

I have a working curl command :

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

I want to execute it through Java.

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

How do I define "--data-binary" argument in the java code.

Abhinav
  • 43
  • 8
  • curl is a program. You are not invoking that program, therefore you are not "executing curl". You are just performing an HTTP request. – Michael Aug 28 '18 at 19:13
  • @Michael This question specifically asks, despite the wording used, how to imitate curl's `--data-binary` in Java. Does that linked duplicate answer this? – FThompson Aug 28 '18 at 19:17
  • You can use Jsoup library. Document doc = Jsoup.connect(url).requestBody("temp,device=xyz value=33").header("Content-Type", "application/x-www-form-urlencoded").post();System.out.println(doc); – Krystian G Aug 28 '18 at 19:34
  • @Vulcan See the section "Uploading files" of the top answer – Michael Aug 28 '18 at 19:35

1 Answers1

0

Running sample code:

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);
}
Shivang Agarwal
  • 1,515
  • 11
  • 18