在java中获取google的搜索结果

问题描述:

我在此程序中收到403响应代码,但我需要获得200才能取回搜索结果,我该怎么办?

I got 403 response code in this program, but I need to get 200 to getting back the search result, what can I do?

      String url="http://www.google.com/search?q=";
      String charset="UTF-8";
      String key="java";
      String query = String.format("%s",URLEncoder.encode(key, charset));
      URLConnection con = new URL(url+ query).openConnection();
      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String inputLine;
      while ((inputLine = in.readLine()) != null) 
      System.out.println(inputLine);
      in.close();


Google阻止了Java发送的默认UserAgent。您可以使用另一个并欺骗Google。只需添加:

Google is blocking the default UserAgent sent by Java. You can use another one and trick Google. Simply add:

con.setRequestProperty(User-Agent,Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10.4; en -US; rv:1.9.2.2)Gecko / 20100316 Firefox / 3.6.2);

创建con后和开始之前读。

after creating the con and before starting to read.