代码之家  ›  专栏  ›  技术社区  ›  Tereno

在Java中处理下载

  •  6
  • Tereno  · 技术社区  · 15 年前

    如何在Java中使用HTTPROSPUNSE处理下载?我向特定站点发出了httpget请求-该站点返回要下载的文件。如何处理此下载?inputstream似乎无法处理它(或者我用错了方法)。

    3 回复  |  直到 8 年前
        1
  •  8
  •   BalusC    15 年前

    假设你说的是 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) {}
            }
        }
    
    }
    

    在这里工作很好。你的问题出在别的地方。

        2
  •  1
  •   Matthew Flynn    15 年前

    打开流并发送文件:

    try {
        FileInputStream is = new FileInputStream( _backupDirectory + filename );
        OutputStream os = response.getOutputStream();
        byte[] buffer = new byte[65536];
        int numRead;
        while ( ( numRead = is.read( buffer, 0, buffer.length ) ) != -1 ) {
            os.write( buffer, 0, numRead );
        }
        os.close();
        is.close();
    }
        catch (FileNotFoundException fnfe) {
        System.out.println( "File " + filename + " not found" );
    }
    
        3
  •  0
  •   N00b Pr0grammer TChia    8 年前

    通常,当您希望浏览器显示要下载的文件的下载对话框时,应设置传入的 inputstream 内容直接进入响应对象蒸汽并设置响应的内容类型( HttpServletResponse 对象)到相关文件类型。

    即。,

    response.setContentType(.. relevant content type)
    

    内容类型可以是 application/pdf 以pdf文件为例。

    如果浏览器有一个插件在浏览器窗口中显示相关文件,文件将打开,用户可以保存,否则浏览器将显示下载框。