问题是您没有读取输出。我修改了你的代码,所以应该工作。我不是100%确定的,因为我出于某种原因无法正确测试它。
编辑 - 它的工作原理,我只是执行错误的命令!这应该适合你。
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();
}
编辑 - 利用ProcessBuilder
代替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);
的可能的复制新的代码[?如何在Java中使用卷曲(http://stackoverflow.com/questions/2586975/how-to -use-curl-in-java) – pczeus