0

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

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();
    }
4

1 回答 1

2

只是另一个 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();
}

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

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

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

于 2013-12-18T21:18:10.053 回答