How to check if a server’s response returns (200 OK) in java ?

Asked

Viewed 756 times

0

I am developing an android app, and would like to check if a site or a URL is active

  • Welcome to the Stackoverflow site. To be able to help you, I need you to explain your question better. Have you tried making your code? Can I post what you already tried? So I check where the error is.

1 answer

1


The verification can be done using Android’s own REST Apis, making a GET call from a URL and waiting for a Response, from this Response you make the logic on top of the Status Code you receive.

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes https://square.github.io/retrofit/2.x/retrofit/retrofit/Response.html

One of Android’s REST Apis - https://square.github.io/retrofit/

Alternatively, use the Java API itself to check, but the package API will be limited java.net

Ex:

public int getStatusCode(String urlPath) {
    try {
        URL url = new URL(urlPath); // http://www.seusite.com.br
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();
        return conn.getResponseCode();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
  • Vlw, fell like a glove!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.