簡體   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