Java 使用 OkHttp 获取 Http 状态码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23980521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Http Status Code with OkHttp
提问by maja
I'm using OkHttp to get the content of some websites.
我正在使用 OkHttp 来获取一些网站的内容。
However, I'm not able to get the Http-Status Code from the response.
但是,我无法从响应中获取 Http-Status 代码。
My Java-Code:
我的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();
This method:
这种方法:
httpResponse.toString();
Returns the following content:
返回以下内容:
Response{protocol=http/1.1, code=200, message=OK, url=https://www.google.at}
Is there a way to get the statusCode as an integer, or do I need a Regular Expression to filter it out of this toString()-method?
有没有办法将 statusCode 作为整数获取,或者我是否需要一个正则表达式来从这个 toString() 方法中过滤掉它?
采纳答案by dinukadev
You can use HttpResponseclass and using that you can access the status code as follows;
您可以使用HttpResponse类并使用它可以访问状态代码如下;
HttpResponse httpResponse = client.newCall(request).execute();
httpResponse.getStatusLine().getStatusCode();
If you are using com.squareup.okhttp.Response then you can use the code() method to get the HTTP status code.
如果您使用 com.squareup.okhttp.Response 那么您可以使用 code() 方法来获取 HTTP 状态代码。
Response httpResponse = client.newCall(request).execute();
httpResponse.code();
回答by savepopulation
You can get response with:
你可以得到回应:
Response response = client.newCall(request).execute();
And get response status code with:
并通过以下方式获取响应状态代码:
int responseCode = response.code();