繁体   English   中英

使用 Apache HttpClient 下载文件

[英]Download file with Apache HttpClient

我想做的是用httpclient下载一个文件。 目前我的代码如下。

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

我的下载 URL 是这样的: http : //example.com/file/afz938f348dfa3

正如您所看到的,文件没有扩展名(至少在 url 中)但是,当我使用普通浏览器访问 url 时,它确实下载了文件“asdasdaasda.txt”或“asdasdasdsd.pdf”(名称与 url 不同,并且扩展名并不总是相同的,这取决于我尝试下载的内容)。

我的 http 响应如下所示:

日期: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" 内容- 类型:文本/普通; charset=UTF-8 变化:接受编码内容编码:gzip 内容长度:2554 保持活动:超时=5,最大=100 连接:保持活动

我怎样才能让我的 java 代码自动下载特定文件夹中具有良好名称和扩展名的文件?

您可以从响应的content-disposition标头中获取文件名和扩展名

首先获取标头,然后按照此处解释的文件名解析它,即:

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

更正式的方法是使用 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.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