手动向网站发送GET请求.302重定向错误

Pyt*_*ord 5 java redirect get http request

我目前正在使用java进行Web scraper.我通过设置tcp连接和使用printerwriter手动发送GET请求.

我可以连接到大多数网站,如yahoo.com或cracked.com并收到回复,但我无法连接到我的目标网站 - vinylengine.com.它总是会返回302错误.

我已经将我的发送请求与我的浏览器进行了比较,它们几乎相同.

我的标题:

GET / HTTP/1.1
Host: www.vinylengine.com
Run Code Online (Sandbox Code Playgroud)

我的回复:

HTTP/1.1 302 Found
Date: Thu, 06 Jun 2013 19:27:00 GMT
Server: Apache
Location: http://www.nakedresource.com/
Cache-Control: max-age=1209600
Expires: Thu, 20 Jun 2013 19:27:00 GMT
Content-Length: 213
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="http://www.nakedresource.com/">here</a>.</p>
</body></html>
Run Code Online (Sandbox Code Playgroud)

浏览器标题:

GET http://www.vinylengine.com/ HTTP/1.1
Host: www.vinylengine.com
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __utma=72407316.18415374.1370488314.1370497873.1370543389.3; __utmz=72407316.1370488314.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); SESSaf8d12283bdbdc5f5bbfb2aef054db6d=1f0676e5cab0ba2c5a80e76ea0bd6f75; __utmc=72407316; has_js=1; __utmb=72407316
Connection: keep-alive
If-Modified-Since: Thu, 06 Jun 2013 18:02:53 GMT
If-None-Match: "2186d59ac297e0f1a43433fa61e8a94b"
Run Code Online (Sandbox Code Playgroud)

码:

public void sendRequest(String extensionString, String urlString)
{  
    try 
    {
        //BufferedReader inFromServer;
        //PrintWriter outToServer;
        //These 2 are initalized elsewhere

        outToServer.println("GET " + extensionString + " HTTP/1.1");
        outToServer.println("Host: " + urlString);

        outToServer.println("");
        outToServer.flush();

        String temp;
        while((temp=inFromServer.readLine()) != null) 
        {
            System.out.println(temp);
        }

        return;
    } 
    catch (Exception e) 
    {
        System.out.printf("sendRequest failed: %s",e);
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试将主机名更改为nakedresource.com,但是当我这样做时,我获得了nakedresource.com的页面源,而不是vinylengine.com

Bri*_*ach 6

有问题的网站正在查看您的用户代理字符串(或者在您的情况下缺少用户代理字符串).

当你说你正在做与浏览器"几乎相同的事情"时......你是对的.计算机对这类事情有点挑剔.

如果您不提供User-Agent:标题,则会获得重定向.

> telnet www.vinylengine.com 80
尝试67.225.154.112 ...
连接到vinylengine.com.
逃脱角色是'^]'.
GET/HTTP/1.1
主机:www.vinylengine.com
接受:*/*

HTTP/1.1 302发现
......

如果您确实提供了一个,那么您将获得该页面:

> telnet www.vinylengine.com 80
尝试67.225.154.112 ...
连接到vinylengine.com.
逃脱角色是'^]'.
GET/HTTP/1.1
主机:www.vinylengine.com
用户代理:curl/7.21.4(universal-apple-darwin11.0)libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5
接受:*/*

HTTP/1.1 200 OK
...(页面)

这通常是因为网站根据User-Agent标题为不同的浏览器提供不同版本的内容.显然他们对"没有用户代理"的回答是...平底船,你被重定向到父站点根目录.