HttpStatus在API级别22中被弃用

时间:2015-04-29 10:40:45

标签: android http rest-client

通常我习惯使用RestClient类在我的org.apache.http.HttpStatus类中检查服务器的不同代码响应,如下例所示:

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;
}

但是根据官方documentation

,最近该课程因API级别22 而被弃用
  

此接口在API级别已弃用   22.请改用openConnection()。有关详细信息,请访问此webpage

但对我使用OpenConnection()方法没有任何意义。

我的问题是:有没有其他方法可以执行相同的功能而无需在应用程序中自行对所有代码响应进行硬编码?

提前致谢。

1 个答案:

答案 0 :(得分:80)

您可以将openConnection的返回值转换为HttpURLConnection,并使用getResponseCode()检索响应代码

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

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

}

HttpURLConnection.getResponseCode()文档为here