【发布时间】: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