Home > Software design >  Java executing curl command not working on some commands
Java executing curl command not working on some commands

Time:12-07

I am using Spring with Java 11.

I have a test curl command that I can call successfully via java.

final String cmdGetDocId = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2";
Process process = Runtime.getRuntime().exec(cmdGetDocId);
InputStream inputStream = process.getInputStream();
JSONObject json = convertToJSON(inputStream);

The returned JSON is as expected.

If I use a different curl and execute it on the command line, it returns some JSON successfully as expected.

curl --location --request GET 'http://xxx.xx.xx.xx:8080/document/details/' --header 'Authorization: Basic xxxxx'

However, if I try to call the curl from my Java application, it fails.

String cmdGetDocId = "curl --location --request GET 'http://xxx.xx.xx.xx:8080/document/details/' --header 'Authorization: Basic xxxxx'";
Process process = Runtime.getRuntime().exec(cmdGetDocId);
InputStream inputStream = process.getInputStream();
JSONObject json = convertToJSON(inputStream);

The returned inputStream is empty.

Do you know what I am doing wrong? Why can the java method call the test curl but not the other GET curl?

CodePudding user response:

I made a minimal example to explain you a few things:

public class Playground {
    public static void main(String... args) throws IOException, InterruptedException {
        String cmdGetDocId = "curl -XGET 'https://google.com'";
        Process process = Runtime.getRuntime().exec(cmdGetDocId);
        InputStream inputStream = process.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        System.out.println("output: ");
        Thread.sleep(2000);
        while(process.isAlive()) Thread.sleep(100);
        System.out.println("return value: "   process.exitValue());
        reader.lines().forEach(System.out::println);
        reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        reader.lines().forEach(System.err::println);
        System.out.println("---");
    }
}

On the one hand, you must make sure, the command is actually finished, when you try to output. In order to make sure, I have this dirty while-loop. Also, you want to have a look at the Error-Output, too.

Also you actually don't want to use cURL inside of your Java Program. There is a ton of beautiful Libraries or even the bare HttpURLConnection.

CodePudding user response:

Try this,

String command = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2";
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process process = builder.start();

InputStream response = process.getInputStream();

This will contain the error if any, Otherwise the reponse.

  • Related