【问题标题】:executing a curl request with a shell command in java?在java中使用shell命令执行curl请求?
【发布时间】: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\'"}};

标签: java shell curl


【解决方案1】:

为什么不为此使用本机 java 方法:HttpURLConnection?正如您在本教程中看到的那样,它有点冗长:http://www.journaldev.com/7148/java-httpurlconnection-example-to-send-http-getpost-requests。更好的是,试试 apache httpclient。它有一个很好的流畅界面,可以让你调用一个简单的 url:

// Execute a GET with timeout settings and return response content as String.
 Request.Get("http://somehost/") .execute().returnContent().asString();

然后您可以使用其中一个 java Jason 库来操作结果。 json-simple 是最容易使用的(但有很多可供选择):https://github.com/fangyidong/json-simple。首先解析上面 http 调用返回的字符串:

Object obj=JSONValue.parse(s);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 2018-05-21
    • 2011-03-04
    相关资源
    最近更新 更多