gpt4 book ai didi

java - 无法从有效的 URL 中读取 HTML 内容

转载 作者:行者123 更新时间:2023-11-29 03:38:27 25 4
gpt4 key购买 nike

我正在尝试一个从给定 URL 读取 HTML 内容的简单程序。我在这种情况下尝试的 URL 不需要任何 cookie/用户名/密码,但我仍然收到 io.IOException: Server returned HTTP response code: 403 错误。谁能告诉我我在这里做错了什么? (我知道在 SO 中有类似的问题,但他们没有帮助):

    import java.net.*;
import java.io.*;
import java.net.MalformedURLException;
import java.io.IOException;
public class urlcont {
public static void main(String[] args) {
try {
URL u = new URL("http://www.amnesty.org/");
URLConnection uc = u.openConnection();
uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
uc.connect();
InputStream in = uc.getInputStream();
int b;
File f = new File("C:\\Users\\kausta\\Desktop\\urlcont.txt");
f.createNewFile();
OutputStream s = new FileOutputStream(f);
while ((b = in.read()) != -1) {
s.write(b);
}
}
catch (MalformedURLException e) {System.err.println(e);}
catch (IOException e) {System.err.println(e);}
}
}

最佳答案

如果您可以在浏览器中获取 URL,但不能通过 Java 获取,那么对我来说,这表明他们正在阻止通过用户代理过滤对页面进行编程访问。尝试在您的连接上设置用户代理,以便您的代码在网络服务器上显示为网络浏览器。

请参阅此主题以获取帮助:What is the proper way of setting headers in a URLConnection?

关于java - 无法从有效的 URL 中读取 HTML 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14280464/

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