我正在尝试从Java运行Linux命令。该命令从命令行本身运行完美,但从Java不运行。 命令行中的命令是
curl -H "Content-Type: text/plain" -d "$(printf '#Genes\nPIK3C2A\nPTEN\nUNC5B')" -X POST --url https://reactome.org/AnalysisService/identifiers/projection/
来自Java的命令是
String $notifyMsg="\"$(printf '#Genes\nPIK3C2A\nPTEN\nUNC5B')\"";
String $reactome = "https://reactome.org/AnalysisService/identifiers/projection/";
String $notifyTitle= "\"Content-Type: text/plain\"";
String $command = "curl" + " " + "-H"+ " " + $notifyTitle + " "+ "-d " + $notifyMsg +" "+ "-X" + " " + "POST" + " " + " " + "--url" +" " + $reactome;
System.out.println("Command is: " + $command);
Process p=Runtime.getRuntime().exec($command);
p.waitFor();
System.out.println("Run Result " + p.exitValue() )
我为了获得这样的输出而感到沮丧
{"summary":{"token":"MjAxODAxMjMxNjQyMDZfNjcy","projection":true,"interactors":false,"type":"OVERREPRESENTATION","sampleName":"Genes","text":true},"expression":{"columnNames":[]},"identifiersNotFound":0,"pathwaysFound":51,"pathways":
但我得到0。谁能告诉我什么可能是错的?
答案 0 :(得分:2)
引用和逃避是你的敌人。最好的办法是完全避免它们。使用一种方法启动该过程,该方法允许您将各个参数作为单独的字符串传递,而不必将它们拆分。
Process p = new ProcessBuilder(
"curl",
"-H", "Content-Type: text/plain",
"-d", "#Genes\nPIK3C2A\nPTEN\nUNC5B",
"-X", "POST",
"--url", "https://reactome.org/AnalysisService/identifiers/projection/"
).start();
您的代码调用exitValue()
,它会为您提供流程的退出代码。要阅读其输出,请从input stream。
InputStream s = p.getInputStream();
答案 1 :(得分:1)
p.exitValue()
会为您提供流程的退出代码。它返回0,因为卷曲成功,退出代码为0。
我会考虑调查HttpClient
library以便在Java中本地执行这些操作。
答案 2 :(得分:1)
这对我有用:
String notifyMsg = "#Genes\nPIK3C2A\nPTEN\nUNC5B";
String reactome = "https://reactome.org/AnalysisService/identifiers/projection/";
String notifyTitle = "Content-Type: text/plain";
Process p = new ProcessBuilder("curl", "-H", notifyTitle, "-d", notifyMsg, "-X", "POST", "--url", reactome).start();
p.waitFor();
try (Scanner scanner = new Scanner(new InputStreamReader(p.getInputStream()))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
System.out.println("Run Result " + p.exitValue());
ProcessBuilder
的vararg构造函数Content-Type
说明和-d
$(printf
是shell解释的东西,但Java却没有。只需在Java字符串文字中使用\n
即可获得新行。我还添加了一些代码来读取输出。