gpt4 book ai didi

java - 将curl与Runtime.getRuntime().exec一起使用

转载 作者:行者123 更新时间:2023-12-02 12:18:51 25 4
gpt4 key购买 nike

我想在 java 程序中使用 Runtime.getRuntime().exec

完整的代码片段如下,但我的问题归结为当我在 Runtime.getRuntime().exec(command),但是当我使用 System.out.println 命令时,将其复制并粘贴到 shell 中并在那里执行,效果很好。

System.out.println(command);
Runtime.getRuntime().exec(command);

什么可能导致运行时 exec 和在 shell 中执行命令之间产生不同的结果。

感谢您的任何提示

马丁

更新:

  • 使用运行时时收到的错误响应是:{"error":"unauthorized"}

  • 正如我从命令中看到的,似乎不清楚。我在运行curl 命令时没有遇到任何异常,但json 响应如上面发布的那样。

<小时/>
String APP_ID = "XXX";
String REST_API_KEY = "YYY";

String header = "-H \"X-Parse-Application-Id: " + APP_ID
+ "\" -H \"X-Parse-REST-API-Key: " + REST_API_KEY
+ "\" -H \"Content-Type: application/zip\" ";

public void post2Parse(String fileName) {

String outputString;

String command = "curl -X POST " + header + "--data-binary '@"
+ fileName + "' https://api.parse.com/1/files/" + fileName;

System.out.println(command);

Process curlProc;
try {
curlProc = Runtime.getRuntime().exec(command);

DataInputStream curlIn = new DataInputStream(
curlProc.getInputStream());

while ((outputString = curlIn.readLine()) != null) {
System.out.println(outputString);
}

} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

最佳答案

我没有直接的答案,但有一点是撇号的编码方式不同。虽然是一个老问题,但我会回答以供将来引用,也许稍后有人可以解释完整的答案。

当我以类似的方式测试我们的 API 时,我注意到以下内容:

curl -i http://localhost:8080/auth/login -d 'identifier=test@example.com&password=test'

此命令从 shell 发送时,最终在服务器中为:

identifier=test@example.com,\npassword=test,\n

但是当从 Runtime.getRuntime().exec(command) 发送时,它最终会是:

'identifier=test@example.com,\npassword=test',\n

如果我更改curl命令并删除撇号,它就会起作用(由于该命令的本质)

 curl -i http://localhost:8080/auth/login -d identifier=test@example.com&password=test

因此,一个事实的猜测是,如果问题中的代码更改为这样,如果文件名不包含空格,它实际上可能会起作用......:

String command = "curl -X POST " + header + "--data-binary @"
+ fileName + " https://api.parse.com/1/files/" + fileName;

一种选择是使用带有输入数组的执行命令,如下所述:Runtime Exec seems to be ignoring apostrophes结合解析curl命令(除非硬编码),如下所述:Split string on spaces in Java, except if between quotes (i.e. treat \"hello world\" as one token)

关于java - 将curl与Runtime.getRuntime().exec一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12453477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com