'How can I run this command from java?

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":"[email protected]", "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\":\"[email protected]\",\"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;
}


Solution 1:[1]

You can go with rest template for external API call.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sandeep Vokkareni