用Java处理下载 [英] Handling downloads in Java

查看:52
本文介绍了用Java处理下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Java中的HttpResponse处理下载?我向特定站点发出了HttpGet请求-该站点返回要下载的文件.如何处理此下载?InputStream似乎无法处理它(或者我使用的是错误的方法.)

How would I be able to handle downloads using HttpResponse in Java? I made an HttpGet request to a specific site - the site returns the file to be downloaded. How can I handle this download? InputStream doesn't seem to be able to handle it (or maybe I'm using it the wrong way.)

推荐答案

假设您实际上是在谈论 SSCCE :

Assuming you're actually talking about HttpClient, Here's an 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) {}
        }
    }

}

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

Works fine here. Your problem lies somewhere else.

这篇关于用Java处理下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆