java - 使用 OkHttp 获取 Http 状态码

标签 java http-status-codes okhttp

我正在使用 OkHttp 来获取一些网站的内容。

但是,我无法从响应中获取 Http 状态代码。

我的 Java 代码:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
                    .url("https://www.google.at")
                    .build();
Response httpResponse = client.newCall(request).execute();    
String html = httpResponse.body().string();

这个方法:

httpResponse.toString(); 

返回以下内容:

Response{protocol=http/1.1, code=200, message=OK, url=https://www.google.at}

有没有办法将 statusCode 获取为一个整数,或者我需要一个正则表达式来将它从这个 toString() 方法中过滤掉?

最佳答案

您可以使用 HttpResponse类并使用它可以访问状态代码,如下所示;

HttpResponse httpResponse = client.newCall(request).execute(); 
httpResponse.getStatusLine().getStatusCode();

如果你使用的是 com.squareup.okhttp.Response 那么你可以使用 code() 方法来获取 HTTP 状态码。

Response httpResponse = client.newCall(request).execute(); 
httpResponse.code();

关于java - 使用 OkHttp 获取 Http 状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23980521/

相关文章:

java - 用 Scala 继承 'object'

java - 有没有人有任何使用循环的简单 JEXL 示例。我想遍历一个简单的数组来输出各种字符串值?

ajax - AJAX问题: server is not returning proper status code in the event of a error

android - 好的 http 默认情况下在请求中设置不需要的 header 。

android - 如何禁用与 OkHttp 的一个连接的重试?

java - 在 Java/JavaScript 中解析 ISO-8601 持续时间

java - Android TextView 中真正的顶部对齐文本

java - 如何使用Spring Boot引发自定义异常而不是500

http-headers - StrongLoop环回: How to customize HTTP response code and header

android - 如何使用 OkHTTP3/Retrofit2 获取多部分多文件上传的进度?