HttpStatus 在 API 级别 22 中被弃用

HttpStatus become deprecated in API level 22

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

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

,最近 class 从 API 级别 22 开始被弃用

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

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

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

提前致谢。

您可以将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