简体   繁体   English

使用 Apache HttpClient 下载文件

[英]Download file with Apache HttpClient

what im trying to do is to download a file with httpclient.我想做的是用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我的下载 URL 是这样的: 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).正如您所看到的,文件没有扩展名(至少在 url 中)但是,当我使用普通浏览器访问 url 时,它确实下载了文件“asdasdaasda.txt”或“asdasdasdsd.pdf”(名称与 url 不同,并且扩展名并不总是相同的,这取决于我尝试下载的内容)。

My http response looks like this:我的 http 响应如下所示:

Date: Mon, 29 May 2017 14:57:14 GMT Server: Apache/2.4.10 Content-Disposition: attachment;日期:2017 年 5 月 29 日星期一 14:57:14 GMT 服务器:Apache/2.4.10 内容处置:附件; 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; 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" 内容- 类型:文本/普通; charset=UTF-8 Vary: Accept-Encoding Content-Encoding: gzip Content-Length: 2554 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive charset=UTF-8 变化:接受编码内容编码:gzip 内容长度:2554 保持活动:超时=5,最大=100 连接:保持活动

How can i do so my java code automatically download the file with the good name and extension in a specific folder ?我怎样才能让我的 java 代码自动下载特定文件夹中具有良好名称和扩展名的文件?

You can get the file name and extension from your response's content-disposition header您可以从响应的content-disposition标头中获取文件名和扩展名

First get the header then parse it for the filename as explained 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();
}

More formal way would be to use HeaderElements API:更正式的方法是使用 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();
    }

Java 11 code to download file using java.net.http.HttpClient使用java.net.http.HttpClient下载文件的Java 11代码

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

... ...

public static void downloadFile(String productId) throws IOException, InterruptedException {
        String url = "https://sameer-platform.com/v1/products/" + productId + "/download/model";

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).build();

        // Creates new File at provided location user.dir and copies the filename from Content-Disposition
        HttpResponse<Path> response = client.send(request,
                HttpResponse.BodyHandlers.ofFileDownload(Path.of(System.getProperty("user.dir")),
                        StandardOpenOption.CREATE, StandardOpenOption.WRITE));

        System.out.println(response.statusCode());
        System.out.println(response.headers());
        Path path = response.body();
        System.out.println("Path=" + path); // Absolute Path of downloaded file
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM