如何在Java中获取URL的HTTP响应代码?

问题

请告诉我获取特定URL的响应代码的步骤或代码。


#1 热门回答(156 赞)

HttpURLConnection

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();

这绝不是一个有力的例子;你需要处理IOException和诸如此类的东西。但它应该让你开始。

如果你需要更多功能的东西,请查看HttpClient


#2 热门回答(33 赞)

URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();

#3 热门回答(10 赞)

你可以尝试以下方法:

class ResponseCodeCheck 
{

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

        URL url = new URL("http://google.com");
        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");
        }
    }
}