2012-07-11 147 views
3

我正在寫一個測試porgram在java中測試我的連接到django restfull api(準確地說是djangorestframework)。 其中一個選項是用捲曲測試api的。 運行從shell curl命令它工作正常: 例如爲:從processbuilder執行curl與java

curl --show-error --request GET --header 'Accept: application/json' --user "user:pwd" http://127.0.0.1:8000/api/v1/ 

這將返回很好的API根URL和幫助文件JSON格式。

現在,當我嘗試調用從Java一樣,採用的ProcessBuilder,我得到這樣的回答:

{"detail": "You do not have permission to access this resource. You may need to login or otherwise authenticate the request."} 

我使用的Java代碼:

ProcessBuilder p=new ProcessBuilder("curl","--show-error", "--request","GET", 
        "--header","'Accept: application/json'", "--user","\"" + userName + ":" + password + "\"", getApiRootUrlString()); 
final Process shell = p.start(); 

因爲我也趕上錯誤流通過:

InputStream errorStream= shell.getErrorStream(); 
InputStream shellIn = shell.getInputStream(); 

我知道他開始curl命令,因爲在其中一個選項中的錯誤顯示t他捲曲幫助文本。

我不確定調用它有什麼區別,很確定它是相同的命令。

順便說一下,「getApiRootUrlString()返回正確的網址:http://127.0.0.1:8000/api/v1/

回答

4

每次傳遞給ProcessBuilder構造函數的字符串代表一個參數,所以你不需要,你將不得不與使用引號貝殼。請嘗試以下操作:

ProcessBuilder p=new ProcessBuilder("curl","--show-error", "--request","GET", 
       "--header","Accept: application/json", "--user", userName + ":" + password, getApiRootUrlString()); 

如果使用引號然後他們成爲傳遞給此過程中的價值的一部分,所以你試圖用"user用戶名和pwd"密碼進行身份驗證。

+0

ahhhh愚蠢的我,當然!感謝名單!我只是測試它,而且......(我在測試之前已經知道你是對的) – 2012-07-11 22:41:39