本文介绍了如何在Java中使用HttpClient检索二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我可以按如下方式检索文本页面

At the moment I can retrieve a text page as follows

    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以二进制文件为目标.如何将其正确保存到磁盘?

Suppose get is targeted at a binary file. How would I save this correctly to disk?

推荐答案

只是不要通过Reader-从InputStream读取数据并写入OutputStream.

Just don't go via a Reader - read the data from the InputStream and write to an 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 {
}

这篇关于如何在Java中使用HttpClient检索二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 02:05