2011-07-12 61 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:编辑... –

相关问题