Download file with Apache HttpClient

 ̄綄美尐妖づ 提交于 2020-01-24 11:26:05

问题


what im trying to do is to download a file with httpclient. At the moment my code is the following.

    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 that: http://example.com/file/afz938f348dfa3

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

My http response looks like this:

Date: Mon, 29 May 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 so my java code automatically download the file with the good name and extension in a specific folder ?


回答1:


You can get the file name and extension from your response's content-disposition header

First get the header then parse it for the filename as explained here, i.e:

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



回答2:


More formal way would be to use 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();
    }


来源:https://stackoverflow.com/questions/44243615/download-file-with-apache-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!