Web 浏览器成功时 Java 程序收到 403 禁止错误
问题:
一个 Java旨在检索给定 Google 搜索查询的结果计数的程序返回403 Forbidden 错误,而相同的查询在 Web 浏览器中会产生结果。代码片段:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; public class DataGetter { public static void main(String[] args) throws IOException { getResultAmount("test"); } private static int getResultAmount(String query) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(new URL("https://www.google.com/search?q=" + query).openConnection() .getInputStream())); String line; String src = ""; while ((line = r.readLine()) != null) { src += line; } System.out.println(src); return 1; } }
错误:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.google.com/search?q=test at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source) at DataGetter.getResultAmount(DataGetter.java:15) at DataGetter.main(DataGetter.java:10)
解决方案:
出现此问题是因为 Java 的 URLConnection 类默认情况下不会伪造实际的用户代理。修改代码以设置用户代理标头可以解决此问题:
URLConnection connection = new URL("https://www.google.com/search?q=" + query).openConnection(); 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(); BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
此外,SSL 处理是透明的,如异常堆栈跟踪所示。
其他注意事项:
检索结果计数涉及进一步的步骤,包括通过获取 cookie 来伪造浏览器解析重定向令牌链接:
String cookie = connection.getHeaderField("Set-Cookie").split(";")[0]; Pattern pattern = Pattern.compile("content=\\"0;url=(.*?)\\""); Matcher m = pattern.matcher(response); if (m.find()) { String url = m.group(1); connection = new URL(url).openConnection(); 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.setRequestProperty("Cookie", cookie); connection.connect(); r = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8"))); sb = new StringBuilder(); while ((line = r.readLine()) != null) { sb.append(line); } response = sb.toString(); pattern = Pattern.compile("<div>
执行此完整代码会产生 2930000000L 的结果。
以上是为什么我的 Java 程序在抓取 Google 搜索结果时会出现 403 禁止错误,而我的浏览器却不会?的详细内容。更多信息请关注PHP中文网其他相关文章!