我有一个URL,当我直接在浏览器中尝试pdf文件时,它将下载pdf文件。但是,当我使用相同的URL使用Java代码中的FileInputStream通过FileInputStream下载文件时,出现了一个问题,例如URL的内容类型是text / html,而不是application / 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 {
//some logic here to download
}
您可以使用应用程序/八位字节流从浏览器下载文件。
也可以使用
Content-Type: application/pdf
Content-Disposition: attachment; filename="fileName.pdf"
Content-Disposition用于告诉您要保存文件而不是显示它。