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

发布于 2024-11-19 23:17:01 字数 583 浏览 2 评论 0原文

目前,我可以检索文本页面,如下所示

    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 的目标是二进制文件。我如何将其正确保存到磁盘?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偷得浮生 2024-11-26 23:17:01

只是不要通过 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 {
}

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 {
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文