2010-04-13 43 views
6

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

+3

你在说什么API /库? [Apache HttpComponents HttpClient v4](http://hc.apache.org/httpcomponents-client/index.html)?如果你不知道,请提及你正在谈论的'HttpResponse'和'HttpGet'类的包名,最好发布一个[SSCCE](http://sscce.org),以便我们发现你的错误。 – BalusC 2010-04-13 20:35:30

+0

的确我在使用Apache HttpComponents。你发布的答案似乎是我正在寻找的。但是,是否有可能将所有输入存储为字符串与实际文件?我的输入流转换为字符串方法使用缓冲读取器,但它给了我空。 – Tereno 2010-04-13 23:11:57

回答

8

假设你实际上是在谈论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) {} 
     } 
    } 

} 

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

+0

我将内容类型添加到头(Application/octet-stream)和使用相同的方法,似乎有伎俩。 – Tereno 2010-04-13 23:25:04

0

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

response.setContentType(.. relevant content type) 

内容类型可以是application/pdf为PDF文件,例如,

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

+0

公平的猜测,但他不是在谈论Servlet API :) – BalusC 2010-04-13 20:42:07

+0

嗯......我认为我因为httpresponse提及而被带走了。对不起:) – Fazal 2010-04-13 21:18:52

1

打开一个流并发送文件:

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