Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 363
Sami Eltamawy Avatar asked Apr 29 '15 10:04

Sami Eltamawy


1 Answers

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

like image 67
Blackbelt Avatar answered Sep 22 '22 19:09

Blackbelt