我想从 Java 执行以下 CURL 命令:
curl -v -X PUT --data-binary "@configfile.json" -u username:password -D /tmp/grabbit_headers http:// server:port/grabbit/job
(http://和 server... 之间的空格是根据堆栈溢出指南插入的,但不是我的代码的一部分)
我已关注
http://alvinalexander.com/java/java-exec-processbuilder-process-1 、进程2和进程3
创建使用 ProcessBuilder API 执行 shell 命令的 java 类。
如果我直接在 shell 上执行 CURL 命令,它就会工作并产生预期的结果。如果我通过 Java 类使用完全相同的命令,它执行时不会出现任何错误,且 exitCode=0,但不会产生预期结果。
此处的预期结果是使用 Grabbit ( https://github.com/TWCable/grabbit ) 将内容从一个 Adobe AEM 实例迁移到另一个实例。
以下是我的主要方法:
public String processBuilderExample() throws IOException, InterruptedException
{
// build the system command we want to run
List<String> commands;
String result="";
/*
* CURL Commands:
* curl -v -X PUT --data-binary "@$configpath" -u $username:$password -D /tmp/grabbit_headers $client$GRABBIT_JOB > /tmp/grabbit
* */
String curl_command="curl -v -X PUT --data-binary \"@"+this.configpath+"\""+" -u "+this.username+":"+this.password+" -D /tmp/grabbit_headers "+this.client+this.GRABBIT_JOB;
commands = new ArrayList<String>(Arrays.asList(curl_command.split(" ")));
result=runCommand(commands);
return result;
}
//@Override
public String runCommand(List<String> commands) throws IOException, InterruptedException
{
// execute the command
SystemCommandExecutor commandExecutor = new SystemCommandExecutor(commands);
int result = commandExecutor.executeCommand();
// get the stdout and stderr from the command that was run
StringBuilder stdout = commandExecutor.getStandardOutputFromCommand();
StringBuilder stderr = commandExecutor.getStandardErrorFromCommand();
StringBuilder finalReturnString=new StringBuilder();
finalReturnString.append("<br/>STDOUT:<br/>");
finalReturnString.append(stdout.toString());
finalReturnString.append("<br/>STDERR:<br/>");
finalReturnString.append(stderr.toString());
return finalReturnString.toString();
}
最佳答案
使用 ProcessBuilder 配置重定向。
">“重定向是 shell (sh/bash) 的一部分,而不是命令。
引用Runtime's exec() method is not redirecting the output关于如何使用流程构建器进行重定向。
引用&> redirection not working correctly为什么它不起作用。
关于java - 为什么我的curl命令不能与Java ProcessBuilder API一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38711208/