1

每次我在使用套接字读取谷歌搜索结果时在我的响应中收到这个错误,每次我搜索它都会给我这个错误响应,有时它给我 302 响应,现在它给我 301,我不知道是什么为此,我只想从谷歌获得结果,每次我被困在这里,如何解决:

HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/search?q=java
Content-Type: text/html; charset=UTF-8
Date: Tue, 26 Feb 2013 10:57:46 GMT
Expires: Thu, 28 Mar 2013 10:57:46 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 232
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
301 Moved
The document has moved here

这是我的代码:

public String readGoogle(String keyword, int page) {
    String content = "";
    try {
        Socket s = new Socket("google.com", 80);
        PrintStream p = new PrintStream(s.getOutputStream());
        p.print("GET /search?q=" + keyword + "&start=" + page
                + " HTTP/1.1\r\n");
        p.print("User-Agent: Mozilla/4.0 "
              + "(compatible; MSIE 7.0; Windows NT 5.1)\r\n");
        p.print("Connection: close\r\n\r\n");
        InputStreamReader in = new InputStreamReader(s.getInputStream());
        BufferedReader buffer = new BufferedReader(in);
        String line;
        while ((line = buffer.readLine()) != null) {
            content += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return content;
}
4

3 回答 3

1

GET在您的请求中输入完整的 URL :

 //           ~~~~~~~~~~~~~~~~~~~~~
 p.print("GET http://www.google.com/search?q=" + keyword + ...
 //           ^^^^^^^^^^^^^^^^^^^^^
 //           ADD THE FULL URL HERE

也许它可以解决你的问题

于 2013-02-26T11:54:19.487 回答
1

301/302 表示服务器要求您重新发出请求(重定向)。要处理此问题,请从响应中读取“位置”标头,然后从服务器提供的 URL 发出新的 GET 请求。在上面的示例中,您被重定向到“ http://www.google.com/search?q=java ”。

或者,您可以下载一个为您处理重定向的库,例如 Apache Http Commons。他们的教程可以在这里阅读教程

于 2013-02-26T12:02:57.073 回答
0

www.google.com根据您的 IP 地址将您重定向到特定国家/地区的站点

还提供了new location,您需要创建一个套接字。

于 2013-02-26T11:36:46.617 回答