gpt4 book ai didi

java - 某些 PDF 文件无法正确下载

转载 作者:行者123 更新时间:2023-11-30 05:47:56 25 4
gpt4 key购买 nike

我对 JAVA 的经验很少(正在开发我的第一个真正的程序),花了几个小时寻找解决方案。我编写了一个小程序来从链接下载 PDF 文件。它适用于大多数链接,但其中一些链接不起作用。

所有有效链接的连接类型均显示为 application/pdf,但某些链接由于某种原因显示为 text/html 连接。

我一直尝试使用我可以在网上找到的任何内容重写代码,但我一直得到相同的结果。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;

public class Main {

public static void main(String[] args) throws Exception {

String link = "https://www.menards.com/main/items/media/UNITE051/SDS/SpectracideVegetationKillerReadyToUse2-228-714-8845-SDS-Feb16.pdf";
String fileName = "File Name.pdf";

URL url1 = new URL(link);

try {
URLConnection urlConn = url1.openConnection();
byte[] buffer = new byte[1024];
double downloaded = 0.00;
int read = 0;

System.out.println(urlConn.getContentType()); // This shows as text/html but it should be PDF

FileOutputStream fos1 = new FileOutputStream(fileName);
BufferedInputStream is1 = new BufferedInputStream(urlConn.getInputStream());
BufferedOutputStream bout = new BufferedOutputStream(fos1, 1024);

try {

while ((read = is1.read(buffer, 0, 1024)) >= 0) {
bout.write(buffer, 0, read);
downloaded += read;
}

bout.close();
fos1.flush();
fos1.close();
is1.close();

} catch (Exception e) {}
} catch (Exception e) {}

}

}

我需要能够从代码中的链接下载 PDF。

这是 PDF 文本文档中保存的内容:

<html>
<head>
<META NAME="robots" CONTENT="noindex,nofollow">
<script src="/_Incapsula_Resource?SWJIYLWA=5074a744e2e3d891814e9a2dace20bd4,719d34d31c8e3a6e6fffd425f7e032f3">
</script>
<body>
</body></html>

最佳答案

该网站实现了一项检查,以确保我正在使用浏览器。我从 Chrome 复制了用户代理,它允许我下载 PDF。

关于java - 某些 PDF 文件无法正确下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54528163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com