使用Apache HttpClient

时间:2017-05-29 13:24:17

标签: java apache download 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();
    }

我的下载网址如下:http://example.com/file/afz938f348dfa3

正如您所看到的那样,文件没有扩展名(至少在网址中)但是,当我使用普通浏览器访问网址时,它会下载文件" asdasdaasda.txt"或" asdasdasdsd.pdf" (名称与url不同,扩展名并不总是相同,取决​​于我试图下载的内容)。

我的http响应如下:

  

日期:2017年5月29日星期一14:57:14 GMT服务器:Apache / 2.4.10   内容 - 处理:附件;文件名=" 149606814324_testfile.txt"   Accept-Ranges:bytes Cache-Control:public,max-age = 0 Last-Modified:   2017年5月29日星期一14:29:06 GMT Etag:W /" ead-15c549c4678-gzip"   内容类型:text / plain; charset = UTF-8 Vary:Accept-Encoding   内容编码:gzip内容长度:2554 Keep-Alive:timeout = 5,   max = 100连接:Keep-Alive

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

3 个答案:

答案 0 :(得分:3)

您可以从回复content-disposition header

中获取文件名和扩展名

首先获取标题,然后将其解析为explained here的文件名,即:

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

答案 1 :(得分:0)

更正式的方法是使用HeaderElements API:

username: appUser
password: SomethingSecretHere

答案 2 :(得分:0)

Java 11 使用 java.net.http.HttpClient

下载文件的代码
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
    }