HttpStatus become deprecated in API level 22
Asked Answered
B

1

43

Usually I used to check for the server different code responses in my RestClient class using the org.apache.http.HttpStatus class as the following example:

if (HttpStatus.SC_OK == restClient.getResponseCode()) {
            //200 OK (HTTP/1.0 - RFC 1945)
            return true;
} else if (HttpStatus.SC_BAD_GATEWAY == restClient.getResponseCode()){
           //502 Bad Gateway (HTTP/1.0 - RFC 1945)
            return false;
}

But recently the class became deprecated since API level 22 according to the official documentation

This interface was deprecated in API level 22. Please use openConnection() instead. Please visit this webpage for further details.

But using OpenConnection() method for me does not make any sense.

My Question is: Is there any other way to do the same functionality without needing to hardcode all the code responses by myself within the application?

Thanks in advance.

Bloat answered 29/4, 2015 at 10:40 Comment(2)
Since HttpClient is deprecated, please, use other clients for http communication. I see no issue with having status codes defined in your code.Preventive
@IgorFilippov listing all the possible CodeResponses is reinventing the wheel . Check out the accepted answer to understand what I meanBloat
O
95

you can cast the returned value of openConnection to HttpURLConnection, and use getResponseCode() to retrieve response code

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
final int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {

} else if (responseCode == HttpURLConnection.HTTP_BAD_GATEWAY) {

}

HttpURLConnection.getResponseCode() documentation is here

Oakley answered 29/4, 2015 at 10:47 Comment(1)
HttpURLConnection.HTTP_OK is exactly what I was looking for. Thanks a lotBloat

© 2022 - 2024 — McMap. All rights reserved.