【问题标题】:Supply browser with input stream for file download [closed]为浏览器提供文件下载的输入流[关闭]
【发布时间】:2013-12-18 20:53:04
【问题描述】:

我有一个输入流连接到服务器上的文件。输入流是使用 Apache Web Components 建立的。如何将该输入流提供给用户的浏览器,以便使用 Apache Web Components 在他们的浏览器中下载文件?

CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("user", "pass"));
    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider).build();
    try {
        HttpGet httpget = new HttpGet("https://website.com/file.txt");

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            InputStream in=entity.getContent();
            int c;
            while((c=in.read())!=-1){
                //maybe write to an ouput stream here so file can download?
                System.out.println(c);
            }

            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

【问题讨论】:

  • 你用什么。 JSP/Servlet 或任何更复杂的框架。请具体说明您的问题。

标签: java http web-component web-client


【解决方案1】:

只是另一个 HTTP 框架:

也许这会有所帮助:

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
   HttpEntity entity = response.getEntity();
   if (entity != null) {
      InputStream instream = entity.getContent();
       try {
          // do something useful
       }  finally {
          instream.close();
      }
  }
} finally {
  response.close();
}

奎尔:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e49

HttpEntity Instanz 为您提供了一个 InputStream,可以使用标准 Java Streaming 类和方法对其进行评估。

可能是一个答案,如果不是,请提供代码 sn-ps 或具体您的问题。

【讨论】:

  • 添加了当前代码。我已经有一个输入流,我需要将该流写入浏览器以便下载文件。
猜你喜欢
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 2012-07-04
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多