Download file from Apache HttpClient

what i am trying to do is download the file using httpclient. At the moment my code is as follows.

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(downloadURL);     


    HttpResponse response = client.execute(request);

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        FileOutputStream fos = new FileOutputStream("C:\\file");
        entity.writeTo(fos);
        fos.close();
    }

      

My download url is something like this: http://example.com/file/afz938f348dfa3

As you can see, there is no extension for the file (at least in the url), however when I go to the url with a normal browser, it downloads the file "asdasdaasda.txt" or "asdasdasdsd.pdf", (the name is different from url, and the extenstion is not always the same, depends on what I'm trying to download).

My http response looks like this:

Date: Mon, May 29, 2017 14:57:14 GMT Server: Apache / 2.4.10 Content-Disposition: attachment; filename = "149606814324_testfile.txt" Accept-Ranges: bytes Cache-Control: public, max-age = 0 Last-Modified: Mon, 29 May 2017 14:29:06 GMT Etag: W / "ead-15c549c4678-gzip "Content-Type: text / plain; charset = UTF-8 Vary: Accept-Encoding Content-Encoding: gzip Content-Length: 2554 Keep-Alive: timeout = 5, max = 100 Connection: Keep-Alive

How can I do this so that my Java code will automatically download a file with a good name and extension in a specific folder?

+3


source to share


2 answers


You can get the filename and extension from your header responsecontent-disposition

First get the header, then parse it for filename like here , ie:



HttpEntity entity = response.getEntity();
if (entity != null) {
    String name = response.getFirstHeader('Content-Disposition').getValue();
    String fileName = disposition.replaceFirst("(?i)^.*filename=\"([^\"]+)\".*$", "$1");
    FileOutputStream fos = new FileOutputStream("C:\\" + fileName);
    entity.writeTo(fos);
    fos.close();
}

      

+3


source


A more formal way would be to use the HeaderElements API:



    Optional<String> resolveFileName(HttpResponse response) {
        return Arrays.stream(response.getFirstHeader("Content-Disposition").getElements())
                .map(element -> element.getParameterByName("filename"))
                .filter(Objects::nonNull)
                .map(NameValuePair::getValue)
                .findFirst();
    }

      

0


source







All Articles