Search code examples
javaandroidhttprequesthttpresponsesynchronous

How is the easiest way to check if the response to the request is succesful or not?


I need a simple synchronous function that checks if the response to a specific url is successful or returns an error, for example 404.

For example:

https://api.com/articles/1 -> response returns sth with code 200

https://api.com/articles/1 -> response returns error 404


Solution

  • As it was already mentioned in the question, you can check the response status.

    • 2xx statuses considered as successful,
    • 3xx can be also turn out as successful, you should use followRedirect.

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

    Depends on the API, it can return with success status, while the response body has content which could still mean an error.

    e.g.: https://www.baeldung.com/java-http-request