0

I am trying to run this command that it ran successfully from the shell but when I create a String it does not run correctly and it is throwing too many errors. This is the command that I want to run:

curl -XPOST 'localhost:9200/_security/user/testUser' -H 'Content-Type: application/json' -d'{"password":"userpassword", "full_name":"user","email":"test@gmail.com", "roles": [ "superuser"]}'

And this the code that I am using:

String s = "curl -XPOST 'localhost:9200/_security/user/testUser' -H 'Content-Type:application/json' -d'{\"password\":\"userpassword\",\"full_name\":\"user\",\"email\":\"test@gmail.com\",\"roles\":[\"superuser\"]}'";

Process process = Runtime.getRuntime().exec(s);
String result = printResults(process);

This is the function:

public String printResults(Process process) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        line += line;
    }
    return line;
}
Abra
  • 19,142
  • 7
  • 29
  • 41
  • And what happens? What are the errors? – passer-by Feb 26 '22 at 02:59
  • 3
    **Java `Process` IS NOT A SHELL. This has been asked and answered many many times.** See https://stackoverflow.com/questions/68222353/ https://stackoverflow.com/questions/59002993/ https://stackoverflow.com/questions/48425729/ https://stackoverflow.com/questions/31776546/ – dave_thompson_085 Feb 26 '22 at 03:42
  • 3
    You shouldn’t use Runtime.exec. [URLConnection](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/net/URLConnection.html) does the same thing, much more reliably. If you’re using a recent version of Java, [HttpClient](https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpClient.html) is even better. – VGR Feb 26 '22 at 03:48
  • You can go with rest template for external API call. – Sandeep Vokkareni Feb 26 '22 at 12:56

0 Answers0