Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

android - HttpStatus become deprecated in API level 22

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.

question from:https://stackoverflow.com/questions/29941328/httpstatus-become-deprecated-in-api-level-22

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...