【发布时间】:2014-05-03 14:07:34
【问题描述】:
我有一些代码,旨在通过 HTTP 向服务器发送 GET 请求,并在那里获取数据。我还没有编写处理响应的部分,因为我首先想测试 GET 请求是否有效。它没有:
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
}
考虑到该代码,fetch() 打印出Status: 403。为什么会这样?我的猜测是这个特定的服务器不允许非浏览器客户端访问它(因为代码适用于http://www.google.com),但有解决方法吗?
已经有一些答案,但其中一些与我无关(他们谈论 HTTPS 的问题)或难以理解。我已经尝试了那些我能理解的,但没有成功。
【问题讨论】:
-
使用 Wireshark 并比较您的浏览器执行的请求和您的编码请求。由于特定的标题行使用丢失/不同,服务器可能会抛出 403。
-
对。我是否查看浏览器发送的标头,并在我的 GET 中复制所有标头?
-
我查看了网站设置的 cookie,它似乎使用了 CloudFlare,它设置了一个
__cfduidcookie。您可能需要handle this cookie。 -
我会试试的。但是,出于兴趣,为什么我需要处理 cookie 以避免 403?