gpt4 book ai didi

HTTP 响应代码为 403 而不是 200,为什么?

转载 作者:可可西里 更新时间:2023-11-01 17:35:57 26 4
gpt4 key购买 nike

当使用 url "https://www.parcelhero.com "时,尽管网站打开成功,但代码给出的 http 响应代码为 403,实际响应代码为 200。请告诉我原因。

  try {
URL url = new URL("https://www.parcelhero.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();

connection.setRequestMethod("GET");

connection.connect();

int code = connection.getResponseCode();
//e.printStackTrace();
System.out.println(code);
}
catch (IOException e) {

e.printStackTrace();
}

最佳答案

一些网站服务器要求在发出请求时设置某些 HTTP header 。否则,他们将在您收到时以 403 响应拒绝该请求。

您只需要使用 connection.setRequestProperty() 设置请求 header 的 User-Agent 属性即可:

        try {
URL url = new URL("https://www.parcelhero.com");
HttpsURLConnection connection = (HttpsURLConnection)
url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
connection.connect();
int code = connection.getResponseCode();
//e.printStackTrace();
System.out.println(code);
}
catch (IOException e) {
e.printStackTrace(System.out);
}

这是一个用于在线测试的工作代码片段:http://rextester.com/ITB98285

关于HTTP 响应代码为 403 而不是 200,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31349554/

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