Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I find the URL response code?

Response response = client . target( url ) . request() . get(); // Looking if response is "200", "201" or "202", for example: if( Arrays.

Can we get the HTTP response code in selenium with Java?

We can get the HTTP response code in Selenium webdriver with Java. Some of the response codes are – 2xx, 3xx, 4xx and 5xx. The 2xx response code signifies the proper condition, 3xx represents redirection, 4xx shows resources cannot be identified and 5xx signifies server problems.

What is a URL response code?

HTTP response status codes (or simply status codes) are three-digit codes issued by a server in response to a browser-side request from a client. These status codes serve as a means of quick and concise communication on how the server worked on and responded to the client's request.


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

import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;

public class API{
    public static void main(String args[]) throws IOException
    {
        URL url = new URL("http://www.google.com");
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        int statusCode = http.getResponseCode();
        System.out.println(statusCode);
    }
}