程序尝试启动与Google的连接时的HTTP响应403?

时间:2013-07-24 19:19:42

标签: java web-crawler httpurlconnection

我已经编写了一个测试网络抓取工具类,试图搜索Google,如下所示:

public class WebCrawler {
String query;

public WebCrawler(String search)
{
    query = search;
}

public void connect()
{
    HttpURLConnection connection = null;
    try 
    {
        String url = "http://www.google.com/search?q=" + query;
        URL search = new URL(url);

        connection = (HttpURLConnection)search.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setAllowUserInteraction(false);
        connection.connect();

        BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        while((line = read.readLine())!=null)
        {
            System.out.println(line);
        }

        read.close();
    }

    catch(MalformedURLException e)
    {
        e.printStackTrace();
    }
    catch(ProtocolException e)
    {
        e.printStackTrace();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        connection.disconnect();
    }
}

}

当我尝试使用测试查询“test”运行它时,我收到HTTP响应403错误 - 我错过了什么?这是我第一次使用Java做任何网络工作。

1 个答案:

答案 0 :(得分:1)

403 ==禁止,这是有道理的,因为你是一个机器人试图访问他们不希望机器人访问的谷歌的一部分。 Google's robots.txt非常明确地指出你不应该抓/搜索。

Google提供search API,每天允许100次查询。它们提供libraries以及如何在大多数语言(包括Java)中与其进行交互的示例。不仅如此,你还得付钱。