在java中获取google的搜索结果 [英] Get search result of google in java

查看:90
本文介绍了在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.

这篇关于在java中获取google的搜索结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆