2016-04-04 33 views
0

當我在我的cmd中打開卷曲時,它的工作。它返回一個json響應。但是輸出對於下面的代碼來說是空白的。在JAVA中使用getRuntime.exec()的CURL

String output = ""; 
      String command = "curl -k -u snehasis:<API KEY> http://example.com"; 
      try { 
       Process p = Runtime.getRuntime().exec(command); 
       p.waitFor(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); 
       String line = ""; 
       while ((line = reader.readLine())!= null) 
       { 
       output.concat(line + "\n"); 
       } 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
    return output; 

不知道我在做什麼錯。請幫助?

+0

你有使用捲曲?對於HttpUrlConnection或Apache HttpClient(或其他Java解決方案)來處理任何棘手的問題? – Thilo

+0

如果輸出很長,'waitFor'會死鎖。 – Thilo

回答

2

這裏:

output.concat(line + "\n"); 

你得到的連接字符串,但你不改變的output值。

Java字符串是不可變的。不要自己改變。你需要改變它們。

用途:

output = output.concat(line + "\n"); 
+0

使用StringBuilder更好。爲什麼要先讀一行呢? – Thilo

+0

@Thilo哦,是的。而且,StringBuilder的字符串也是可變的! – Hackerdarshi

+0

謝謝@Hackerdarshi。不知道我是如何錯過的:) – david419