I am trying to execute a curl command (which works in the terminal) through my java application. I have tried using a process Builder as well as a Runtime.exec()
. I am able to connect, but the response either says
{"result":0,"reason":"Unknown Json request format"}
or
{"result":0,"reason":"Invalid client request Json string"}.
Here is the curl command that works in the terminal:
curl -X POST -d '{"command":"get","user":"R16","id":5552}' "http://<Ex.webaddress>"
When running this, the connection fails
String testCurlCommand = "curl -X POST -d '{\"command\":\"get\",\"user\":\"R16\",\"id\":5552}' \"http://<Ex.webaddress\"";try {
//final Process terminal = curlCommand.start();
Process p = Runtime.getRuntime().exec(testCurlCommand);
try {
String responseString = readInputStream(p.getInputStream());
JSONObject job = new JSONObject(responseString);
// job.getString("Parameter")
statusLabel.setText("Command Result: " + job.toString());
connectionStatusLabel.setText("Connection Status: Successful");
} catch (JSONException e) {
statusLabel.setText("Command Result: 0");
connectionStatusLabel.setText("Connection Status: Failed");
}
} catch (IOException ex) {
statusLabel.setText("Command Result: 0");
connectionStatusLabel.setText("Connection Status: Failed");
}
When changing the String testCurlCommand by removing the quotes around the web address, the connection works but I get the "unknown Json request format"
String testCurlCommand = "curl -X POST -d '{\"command\":\"get\",\"user\":\"R16\",\"id\":5552}' http://<Ex.webaddress";
Ive tried removing the escaped quotes and I still get the same. Ive also tried with process builder:
ProcessBuilder testCurlCommand = new ProcessBuilder("curl", "-X", "POST", "-d", "'{\"command\":\"get\",\"user\":\"R16\",\"id\":\"5552\"}'", "\"http://<examplewebaddress>\"")
I think its something to do with the formating (extra quote or something) but I'm not sure. Any help is greatly appreciated.I will add the readInputStream function below:
static private String readInputStream(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "UTF-8"));
String tmp;
StringBuilder sb = new StringBuilder();
while ((tmp = reader.readLine()) != null) {
sb.append(tmp).append("\n");
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') {
sb.setLength(sb.length() - 1);
}
reader.close();
return sb.toString();
}