[英]Unable to download file with content type text/html
我有一個 URL ,當我直接在瀏覽器上嘗試時,它將下載 pdf 文件。 But when I use the same URL to download the file using FileInputStream in Java code, I'm getting an issue like a content type of URL is text/html, instead of application/pdf because of which we are unable to open the file as URL 中的內容類型不是 pdf。
困惑來了,當內容類型不是應用程序/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();
}
在您的情況下,它看起來像 url 被重定向到另一個 URL 從中下載真實內容。
您需要檢查Location
header ,如果它不是 null 則從 header 關閉連接並在該鏈接上打開新的連接。
然后,當您調用方法 getContentType() 時,它將是 application/pdf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.