【问题标题】:Unable to download file with content type text/html无法下载内容类型为 text/html 的文件
【发布时间】:2020-08-06 12:50:13
【问题描述】:

我有一个 URL,当我直接在浏览器上尝试时,它会下载 pdf 文件。但是,当我使用 Java 代码中的 FileInputStream 使用相同的 URL 下载文件时,我遇到了一个问题,例如 URL 的内容类型是 text/html,而不是 application/pdf,因此我们无法打开文件为URL 中的内容类型不是 pdf。

困惑来了,我怎么能在内容类型不是application/pdf的情况下从浏览器下载文件?

代码有什么问题吗?

String pdfUrl = service.getPdfUrl(bpaRequest);
URL url1 = new URL(pdfUrl);
FileOutputStream fos1 = new FileOutputStream(fileName);
System.out.print("Connecting to " + url1.toString() + " ... ");
URLConnection urlConn = url1.openConnection();

// Checking whether the URL contains a PDF
if (!urlConn.getContentType().equalsIgnoreCase("application/pdf")) {
    throw new CustomException("INVALID_CONTENT", "contentType is not pdf");
} else {
    InputStream is1 = url1.openStream();
    while ((baLength = is1.read(ba1)) != -1) {
        fos1.write(ba1, 0, baLength);
    }
    fos1.flush();
    fos1.close();
    is1.close();
}

【问题讨论】:

  • 我认为您需要使用 application/octet-stream 进行文件下载。

标签: java pdf url content-type fileinputstream


【解决方案1】:

在您的情况下,看起来 url 被重定向到另一个从中下载真实内容的 URL。

您需要检查Location 标头,如果它不为空,则从标头关闭连接中获取值并在该链接上打开新的。

然后当您调用方法 getContentType() 时,它将是 application/pdf

【讨论】:

  • 但是我获取的 URL 的内容类型是 text/html,我可以明确地设置内容类型吗?
  • 内容类型可以是任何文本/html等。更新答案
  • 你想让我为 URL 设置 Content-Disposition 吗?
  • 请显示完整样本
  • 请分享您下载的网址,我试过docs.spring.io/spring-boot/docs/current/reference/pdf/… 工作正常
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-24
  • 2012-03-28
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 2014-03-11
  • 2014-09-17
相关资源
最近更新 更多