如何在Java中使用HttpClient来检索二进制文件?

时间:2011-07-12 06:18:49

标签: 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();
    }

假设get是针对二进制文件的。如何将其正确保存到磁盘?

1 个答案:

答案 0 :(得分: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 {
}