【问题标题】:Download file with Apache HttpClient使用 Apache HttpClient 下载文件
【发布时间】:2017-05-29 13:24:16
【问题描述】:

我想要做的是用 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

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

我的 http 响应如下所示:

日期:2017 年 5 月 29 日星期一 14:57:14 GMT 服务器:Apache/2.4.10 内容处置:附件;文件名="149606814324_testfile.txt" 接受范围:字节缓存控制:公共,最大年龄 = 0 最后修改: 2017 年 5 月 29 日星期一 14:29:06 GMT Etag: W/"ead-15c549c4678-gzip" 内容类型:文本/纯文本; charset=UTF-8 变化:接受编码 内容编码:gzip 内容长度:2554 保持活动:超时 = 5, max=100 连接:保持活动状态

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

【问题讨论】:

  • 您可能想要this header,但当然这实际上取决于服务器如何提供文件;显示请求 URL 时收到的纯 HTTP 响应示例,或提供您正在使用的有效可访问 URL 以获得更多帮助
  • @OvidiuDolha 日期:2017 年 5 月 29 日星期一 14:57:14 GMT 服务器:Apache/2.4.10 内容处置:附件;文件名 =“149606814324_testfile.txt”接受范围:字节缓存控制:公共,最大年龄 = 0 最后修改时间:星期一,2017 年 5 月 29 日 14:29:06 GMT Etag:W/“ead-15c549c4678-gzip”内容-类型:文本/纯文本; charset=UTF-8 变化:Accept-Encoding Content-Encoding:gzip Content-Length:2554 Keep-Alive:timeout=5,max=100 Connection:Keep-Alive

标签: java apache download httpclient


【解决方案1】:

您可以从回复的content-disposition header 中获取文件名和扩展名

首先获取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();
}

【讨论】:

  • 非常感谢,您的代码似乎运行良好。但是我用这一行编写了第一个版本: String fileName = disposition.substring(disposition.indexOf("\"") + 1, disposition.lastIndexOf("\""));而不是 String fileName = disposition.replaceFirst("(?i)^.*filename=\"([^\"]+)\".*$", "$1"); 两者有什么区别?似乎都给出了相同的结果
  • @retArdos 你的方法更简单
【解决方案2】:

更正式的方式是使用 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();
    }

【讨论】:

    【解决方案3】:

    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
        }
    

    【讨论】:

      猜你喜欢
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      相关资源
      最近更新 更多