Java Program Receiving 403 Forbidden Error While Web Browsers Succeed
Problem:
A Java program designed to retrieve the result count for a given Google search query returns a 403 Forbidden error, while the same query yields results in web browsers. Code snippet:
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; } }
Error:
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)
Solution:
The issue arises because Java's URLConnection class does not fake an actual user-agent by default. Modifying the code to set a user-agent header resolves this problem:
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")));
Additionally, SSL handling is transparent, as indicated by the exception stacktrace.
Further Considerations:
Retrieving result counts involves further steps, including faking a browser by fetching cookies and parsing redirect token links:
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>
Executing this full code yields a result of 2930000000L.
The above is the detailed content of Why Does My Java Program Get a 403 Forbidden Error When Scraping Google Search Results While My Browser Doesn't?. For more information, please follow other related articles on the PHP Chinese website!