Artemio Ramirez Artemio Ramirez - 7 months ago 46
Java Question

Java - Using Runtime to run curl command gets blocked by proxy

I'm trying to run a curl command that consumes a webservice I'm running:

String curl = "curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{\"field1\": \"value1\", \"field2\": \"value2\"}' 'http://localhost:8080/service'";
System.out.println(curl);
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(curl);
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}


If I copy the log message from the Sysout and paste it on my terminal, it runs as expected, but when I run the java code, it seems to return an html page from the proxy not finding the service.

Do I have to add something else for it to run from java?

Answer

The problem is that you don't have it read the output. I modified your code so it should work. I'm not 100% sure because I can't test it properly for some reason.

EDIT - It works, I was just executing the wrong command! This should work for you.

String curl = "curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{\"field1\": \"value1\", \"field2\": \"value2\"}' 'http://localhost:8080/service'";
System.out.println(curl);
try {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(curl);
    process.waitFor();
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); //BufferedReader to read the output
    StringBuilder sb = new StringBuilder(); //What will hold the entire console output
    String line = ""; //What will hold the text for a line of the output
    while ((line = reader.readLine()) != null) { //While there is still text to be read, read it
        sb.append(line + "\n"); //Append the line to the StringBuilder
    }
    System.out.println(sb); //Print out the full output
} catch (Exception e) {
    e.printStackTrace();
}

EDIT - New code utilising ProcessBuilder instead of Runtime

String curl = "curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{\"field1\": \"value1\", \"field2\": \"value2\"}' 'http://localhost:8080/service'";
ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", curl);
builder.redirectErrorStream(true);
Process p = builder.start();
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
int linenum = 0;
while (true) {
    linenum++;
    line = r.readLine();
    if (line == null) {
        break;
    }
    sb.append(line);
}
System.out.println(sb);