HttpStatus become deprecated in API level 22

2020-02-18 04:32发布

问题:

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.

回答1:

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