Supply browser with input stream for file download

1.7k Views Asked by At

I have an input stream connected to a file on a server. The input stream was established with using Apache Web Components. How do I provide that input stream to a user's browser so the file will download in their browser using 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();
    }
1

There are 1 best solutions below

1
On

Just another HTTP Framework:

Maybe this helps:

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

The HttpEntity Instanz offers you an InputStream which can be evaluated with standard Java Streaming classes and methods.

Could be an answer, if not pls provide code snippets or concrete your problem.