2011-07-12 101 views
2

目前如下如何在Java中使用HttpClient來檢索二進制文件?

HttpClient client = new DefaultHttpClient(); 
    HttpGet get = new HttpGet(
      "http://google.com"); 

    try { 


     HttpResponse response = client.execute(get); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(
       response.getEntity().getContent())); 

     String line = ""; 
     while ((line = rd.readLine()) != null) { 
      System.out.println(line); 


     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

假設得到的是針對二進制文件,我可以檢索的文本頁面。我將如何正確保存到磁盤?

回答

7

只是不要通過Reader去 - 從InputStream讀取數據並寫入OutputStream

// Using Guava (guava-libraries.googlecode.com) 
InputStream data = response.getEntity().getContent(); 
try { 
    OutputStream output = new FileOutputStream(filename); 
    try { 
     ByteStreams.copy(data, output); 
    } finally { 
     Closeables.closeQuietly(output); 
    } 
} finally { 
} 
+0

我得到一個錯誤的方法複製(InputSupplier <擴展的InputStream?>,文件)的文件類型是不適用的參數(InputStream中,文件) – deltanovember

+0

@deltanovember:編輯... –

相關問題