2015-09-27 135 views
-1

我想知道如何爲我在網上找到的API運行這個命令行代碼。該API要我運行的代碼去如下:在java中使用shell命令執行curl請求?

curl -i "https://api-fxtrade.oanda.com/v1/prices?instruments=EUR_USD"

此代碼將使數據回JSON響應。我試圖通過運行這個拋出一個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命令的知識?感謝您的幫助!!!

+0

我推薦一些本地方法(Request類)。如果你仍然想用exec來做,你應該把命令作爲一個String []來傳遞,第一個元素是shell。 'String [] cmd = {{「/ bin/bash /」},{「curl」},{「-i」},{「'https://api-fxtrade.oanda.com/v1/prices ?儀器= EUR_USD \'「}};' – erip

回答

0

爲什麼不使用原生的java方法:HttpURLConnection?這是一個有點長的囉嗦,你可以在本教程中看到:http://www.journaldev.com/7148/java-httpurlconnection-example-to-send-http-getpost-requests。更好的是,嘗試apache httpclient。它有一個很好的流體界面,可以讓你打電話一樣簡單網址爲:

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

然後你就可以使用Java傑森圖書館之一操縱的結果。 json-simple是最容易使用的(但有很多可供選擇):https://github.com/fangyidong/json-simple。你首先解析由上面的http調用返回的字符串:

Object obj=JSONValue.parse(s);