打开URLConnection后出现奇怪的状态403

时间:2016-02-21 08:39:29

标签: java httpurlconnection

我想知道为什么这个示例代码:

public class Test {

    public static void main(String[] args) throws IOException {
        testLink("http://google.com");
        testLink("http://stackoverflow.com");
        testLink("http://docs.oracle.com");
    }

    private static void testLink(String urlStr) throws IOException
    {
        URL url = new URL(urlStr);

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.connect();
        System.out.println(conn.getResponseCode());
        conn.disconnect();
    }
}

通常打印:

200
403
200

而不是:

200
200
200

1 个答案:

答案 0 :(得分:0)

根据Wikipedia,403响应通常表示以下两种情况之一:

  

提供了身份验证,但不允许经过身份验证的用户执行请求的操作。

     

禁止所有用户操作。例如,当目录列表被禁用时,对目录列表的请求返回代码403。

所以很可能通过User-Agent禁止连接到SO。