2017-07-11 46 views
-1

我正在嘗試使用java.net.URLConnection進行卷曲請求。 但是,我需要在使用--verbose開關執行時分析命令的輸出。Java使用URLConnection來捲曲--verbose開關

以下代碼按預期執行curl請求,我只是在尋找一種獲取命令的詳細輸出的方法。

 String stringUrl = this.contUrl + "/auth?action=login"; 
     URL url = new URL(stringUrl); 
     URLConnection uc = url.openConnection(); 

     System.out.println(stringUrl); 
     System.out.println("Authorization: " + this.header); 

     uc.setRequestProperty("X-Requested-With", "Curl"); 
     uc.setRequestProperty("Authorization", this.header); 

     BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); 
     String result = ""; 
     String line;  
     while((line = in.readLine()) != null) { 
      result += line; 
     } 
+0

你的問題是什麼?什麼是--verbose開關? –

+0

'curl'是一個命令行工具。你沒有運行'curl',你運行的是Java代碼,所以沒有「curl請求」這樣的東西。假設'this.contUrl'的值以'http:'開頭,那麼你正在做一個「HTTP請求」。如果你想讓你的Java代碼寫出類似於''--verbose'](https://curl.haxx.se/docs/manpage.html#-v)爲'curl'所做的輸出,這取決於你編寫代碼以打印請求和響應頭文件,可通過['URLConnection'](https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#method.summary )。 – Andreas

+1

@TuyenNguyen看到'curl'手冊頁:https://curl.haxx.se/docs/manpage.html#-v – Andreas

回答

0

我有一個功能來讀取命令行輸出,希望這幫助:

private String readCommandOutput(String pattern) throws IOException { 
    BufferedInputStream bis = new BufferedInputStream(uc.getInputStream()); 
    ByteArrayOutputStream buf = new ByteArrayOutputStream(); 
    String charset = "utf-8"; 
    int result = bis.read(); 
    String output = ""; 
    String lineSeparator = System.getProperty("line.separator"); 
    while (result != -1) { 
     buf.write((byte) result); 
     output = buf.toString(charset); 
     if (!output.equals(lineSeparator)) { 
      String output_arr[] = output.split(lineSeparator); 
      String lastLine = output_arr[output_arr.length - 1]; 

      // check if this is the end of stream and the pattern is match 
      if (lastLine.endsWith(pattern) && bis.available() == 0) { 
       return output; 
      } 
     }   
     result = bis.read(); 
    } 
    return buf.toString(charset); 
} 

此代碼我用了pattern是一個字符串,以確定何時將命令完成它的工作停止從流中讀取。我不知道你的程序的輸出是什麼,你可以參考我的代碼來修改適合你的程序。