android - HttpStatus 在 API 级别 22 中被弃用

标签 android http rest-client

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

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 起已弃用

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

关于android - HttpStatus 在 API 级别 22 中被弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29941328/

相关文章:

angular - 一个订阅执行两个 HTTP 请求 - Angular 4

ruby-on-rails - 如何正确格式化 json 以使用 RestClient 发送

ruby-on-rails - RestClient::Request.execute传递哈希集

android - 无法将标题 View 添加到列表 - setAdapter 已被调用

java - Android 使用 Retrofit 和 OkHttp 获取 Endpoints

http - 通过 SSL 登录但在非 SSL 页面上显示帐户名?

ruby rest_client 异常处理

java - 使用 Assets 文件夹中的文本文件来匹配并重定向到下一个 Activity

Android kcm 文件似乎不起作用。我错过了什么?

python - 在 Python 中重启 HTTP 服务器的正确方法