[英]Java HTTP GET request gives 403 Forbidden, but works in browser
I have some code, which is meant to send a GET request via HTTP to a server, and fetch the data there. 我有一些代码,该代码旨在通过HTTP向服务器发送GET请求,并从中获取数据。 I haven't yet coded the part that does stuff with the response, as I first wanted to test whether the GET request worked. 我还没有编写处理响应内容的部分,因为我首先想测试GET请求是否有效。 And it didn't: 而且没有:
private static String fetch() throws UnsupportedEncodingException, MalformedURLException, IOException {
// Set the parameters
String url = "http://www.futhead.com";
String charset = "UTF-8";
//Fire the request
try {
URLConnection connection = new URL(url).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
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");
// ^^^ I tried this, and it doesn't help!
InputStream response = connection.getInputStream();
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("GET");
System.out.println("Status: " + httpConnection.getResponseCode());
} catch (UnknownHostException e) {
// stuff
}
return null;
// ^^^ I haven't coded the fetching itself yet
}
With that code in mind, fetch()
prints Status: 403
. 考虑到该代码, fetch()
打印Status: 403
。 Why is this happening? 为什么会这样呢? My guess is that this particular server doesn't let non-browser clients access it (because the code works with http://www.google.com
), but is there a workaround? 我的猜测是该特定服务器不允许非浏览器客户端访问它(因为该代码可与http://www.google.com
),但是有解决方法吗?
There are some answers out there already, but some of them are either irrelevant to me (they talk about a problem with HTTPS) or incomprehensible. 已经有一些答案了,但是其中一些对我来说无关紧要(他们谈论的是HTTPS问题)或难以理解。 I've tried those that I can understand, to no avail. 我尝试了我能理解的那些,但无济于事。
You might have Browser Integrity Check enabled https://support.cloudflare.com/hc/en-us/articles/200170086-What-does-the-Browser-Integrity-Check-do- 您可能启用了浏览器完整性检查https://support.cloudflare.com/hc/en-us/articles/200170086-What-does-the-Browser-Integrity-Check-do-
I disabled Browser Integrity Check and it works fine now. 我禁用了浏览器完整性检查,现在可以正常使用了。 Another solution would be to set User-Agent, if possible. 如果可能的话,另一种解决方案是设置User-Agent。
I experienced the problem from Scala, which eventually uses java.net.URL 我从Scala经历了这个问题,最终使用了java.net.URL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.