【问题标题】:HttpStatus become deprecated in API level 22HttpStatus 在 API 级别 22 中被弃用
【发布时间】:2015-04-29 10:40:45
【问题描述】:

通常我使用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 起已弃用

此接口在 API 级别已弃用 22. 请改用openConnection()。请访问此webpage 了解更多详情。

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

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

提前致谢。

【问题讨论】:

  • 由于 HttpClient 已被弃用,请使用其他客户端进行 http 通信。我认为在您的代码中定义状态代码没有问题。
  • @IgorFilippov 列出所有可能的CodeResponses 正在重新发明轮子。查看接受的答案以了解我的意思

标签: android http rest-client


【解决方案1】:

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

【讨论】:

  • HttpURLConnection.HTTP_OK 正是我想要的。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 2020-12-22
  • 2020-11-09
  • 2023-03-18
  • 1970-01-01
  • 2013-06-02
  • 2023-03-17
相关资源
最近更新 更多