2016-04-22 61 views
1

我试图运行curl命令消耗一个WebService我运行:爪哇 - 使用运行时运行curl命令被阻止代理

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(); 
} 

如果我复制从系统输出的日志信息和粘贴在我的终端上,它按预期运行,但是当我运行java代码时,它似乎从代理返回一个html页面而没有找到服务。

我是否需要添加其他东西才能从java运行?

+0

的可能的复制新的代码[?如何在Java中使用卷曲(http://stackoverflow.com/questions/2586975/how-to -use-curl-in-java) – pczeus

回答

1

问题是您没有读取输出。我修改了你的代码,所以应该工作。我不是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); 
+0

非常感谢你,最后现在我从卷曲中得到一些反馈,由于代理服务器似乎失败了,但是如果我自己在终端中运行命令,它可以工作,所以我仍然不完全明白什么是错的。 –

+0

也许Java程序需要更多权限?这可能是问题所在。尝试用'sudo'运行它? – Dankrushen

+0

嗯,我有一个想法,如果前一个不起作用。尝试使用''String curl =“/ bin/bash -c curl -X POST -header'Content-Type:application/json'--header'Accept:application/json'-d'{\”field1 \“:\ “value1 \”,\“field2 \”:\“value2 \”}''http:// localhost:8080/service'“;'。这将运行命令使用终端 – Dankrushen