2012-09-17 47 views
2

我想使用調用Runtime.getRuntime在Java程序中使用捲曲(時)EXEC的java - 使用curl與調用Runtime.getRuntime(時)EXEC

完整的片段低於但什麼我的問題歸結爲是。我得到一個錯誤的反應,當我在調用Runtime.getRuntime()使用curl命令。EXEC(命令),但是當我的System.out.println的命令,複製並粘貼到一個shell並執行它有它工作正常。

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

什麼可能會導致運行時執行exec和在shell中執行該命令的這種不同結果。

感謝任何提示

馬丁

更新:

  • 錯誤響應,我得到使用運行時爲:{ 「錯誤」: 「未經授權」}

  • 正如我從似乎不清楚的命令中看到的那樣。我沒有得到任何異常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(); 
    } 
} 
+1

郵政異常/錯誤你得到 – CloudyMarble

+0

{「錯誤」:「未經授權」} – dorjeduck

+0

你得到一個異常?它有哪些錯誤代碼和消息?或者輸出顯示未經授權?與發佈響應JSON – CloudyMarble

回答

0

我猜你從捲曲而不是例外的錯誤代碼,再次檢查了Curl API,U猜你會發現像「用戶」或其他任何東西缺少的參數。

你可以嘗試檢查一下this提到的提示。

+0

謝謝 - 是的,不是一個例外,而是提到的錯誤響應。 curl命令在shell中執行時非常相似,所以在Curl API的這一邊似乎沒有問題... – dorjeduck

+0

我看到了這篇文章,但爲了簡單起見,我決定按照一條評論有 – dorjeduck

2

我沒有直接的答案,但有一點是,撇號得到不同的編碼。雖然這是一個老問題,但我會回答以備將來參考,也許有人可以在稍後解釋完整答案。

當我以同樣的方式測試我們的API,我注意到以下幾點:

[email protected],\npassword=test,\n 

但送時:

curl -i http://localhost:8080/auth/login -d '[email protected]&password=test' 

此命令,從外殼發送時,在服務器結束從Runtime.getRuntime().exec(命令),它結束爲:

'[email protected],\npassword=test',\n 

如果我改變curl命令和重新移動撇號,它的工作原理(由於此命令的精華)

curl -i http://localhost:8080/auth/login -d [email protected]&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)

+0

你救了我的生命先生。我在這堵牆上撞了幾個小時。我想簡單地從gradle上傳一個curl文件(作爲一個快速實現),這比預期的要長得多幹杯! – Larusso

相關問題