【发布时间】:2015-09-27 21:47:21
【问题描述】:
我想知道如何为我在网上找到的 API 运行这个命令行代码。 API 希望我运行的代码如下:
curl -i "https://api-fxtrade.oanda.com/v1/prices?instruments=EUR_USD"
此代码将以 JSON 响应的形式返回数据。我试图通过运行 this throwed a shell 命令来实现这一点。我的代码如下:
import java.io.*;
public class FxTest {
public static void main(String[] args) {
FxTest obj = new FxTest();
String command = "curl -i \"https://api-fxtrade.oanda.com/v1/prices?instruments=EUR_USD\"";
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
当我运行这段代码时,我得到了这个错误:
java.io.IOException: Cannot run program "curl": CreateProcess error=2, The system cannot find the file specified
shell 命令是否会执行我正在尝试执行的代码,或者它们是否是解决此问题的更好方法?如果无法在 shell 命令中执行此代码,我有哪些选项,这些选项如何工作以及我应该在哪里了解更多信息。如果 shell 命令是解决这个问题的好方法,那么我的代码有什么问题,我应该在哪里学习更多关于如何使用 shell 命令的信息?谢谢你的帮助!!!
【问题讨论】:
-
我推荐一些本机方法(请求类)。如果您仍想使用 exec 执行此操作,则应将命令作为
String []传递,第一个元素是 shell。String [] cmd = { {"/bin/bash/"}, {"curl"}, {"-i"}, {"'https://api-fxtrade.oanda.com/v1/prices?instruments=EUR_USD\'"}};