0

这是我使用的代码:

class ResponseCodeCheck 
{

public static void main (String args[]) throws Exception
{

    URL url = new URL("http://www.amazon.co.jp/gp/seller/sell-your-stuff.html");
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod("GET");
    connection.connect();

    int code = connection.getResponseCode();
    System.out.println("Response code of the object is "+code);
    if (code==200)
    {
        System.out.println("OK");
    }
}
}

当该 URL 工作正常时,它为 URL 提供了 404。有什么理由吗?

4

2 回答 2

2

为“User-Agent”添加适当的标头值

connection.addRequestProperty("User-Agent", "Safari");
于 2012-07-03T11:04:24.510 回答
0

CURL是说:

curl -v http://www.amazon.co.jp/gp/seller/sell-your-stuff.html
* About to connect() to www.amazon.co.jp port 80 (#0)
*   Trying 176.32.120.128... connected
> GET /gp/seller/sell-your-stuff.html HTTP/1.1
> User-Agent: curl/7.23.1 (x86_64-pc-win32) libcurl/7.23.1 OpenSSL/0.9.8r zlib/1.2.5
> Host: www.amazon.co.jp
> Accept: */*
>
< HTTP/1.1 301 MovedPermanently

请注意HTTP/1.1 301 MovedPermanently。你确定你收到了404而不是301?这是通常的网络实践,301 标头意味着内容被放置在其他位置,用户(浏览器)应该导航到它。

另外请确保HttpURLConnection允许重定向。

于 2012-07-03T11:02:36.460 回答