How to get HTTP response code for a URL in Java? How to get HTTP response code for a URL in Java? java java

How to get HTTP response code for a URL in Java?


HttpURLConnection:

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

This is by no means a robust example; you'll need to handle IOExceptions and whatnot. But it should get you started.

If you need something with more capability, check out HttpClient.


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


You could try the following:

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");        }    }}