java - 在 Java 中处理下载

标签 java apache-httpcomponents

我如何使用 Java 中的 HttpResponse 处理下载?我向特定站点发出了 HttpGet 请求 - 该站点返回要下载的文件。我该如何处理这个下载? InputStream 似乎无法处理它(或者我使用它的方式不对。)

最佳答案

假设您实际上是在谈论 HttpClient , 这是一个 SSCCE :

package com.stackoverflow.q2633002;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class Test {

    public static void main(String... args) throws IOException {
        System.out.println("Connecting...");
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet("http://apache.cyberuse.com/httpcomponents/httpclient/binary/httpcomponents-client-4.0.1-bin.zip");
        HttpResponse response = client.execute(get);

        InputStream input = null;
        OutputStream output = null;
        byte[] buffer = new byte[1024];

        try {
            System.out.println("Downloading file...");
            input = response.getEntity().getContent();
            output = new FileOutputStream("/tmp/httpcomponents-client-4.0.1-bin.zip");
            for (int length; (length = input.read(buffer)) > 0;) {
                output.write(buffer, 0, length);
            }
            System.out.println("File successfully downloaded!");
        } finally {
            if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
            if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
        }
    }

}

在这里工作正常。您的问题出在其他地方。

关于java - 在 Java 中处理下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2633002/

相关文章:

java - 如何在 Play 2.5.x (Scala) 中禁用弱密码和客户端重新协商

android - 如何在Android平台覆盖or.apache.http

apache-camel - Camel Exchange getbody 的文件对象为空

java - Java 程序中 SSLKEYLOGFILE 的等价物是什么?

java - 如何停止camel http重试

java - javax.persistence 中的 ManyToMany 允许重复条目

java - 使用堆栈的二叉搜索树的中序树遍历算法

java - 在 Android 中导入更新的 Apache HttpClient jar

java - 使用接口(interface)时如何为类赋值?

java - 无法为 JSP : BooksWorker cannot be resolved 编译类