Get Http Status Code with OkHttp
Asked Answered
C

3

34

I'm using OkHttp to get the content of some websites.

However, I'm not able to get the Http-Status Code from the response.

My Java-Code:

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?

Caceres answered 1/6, 2014 at 13:46 Comment(0)
A
68

You can use HttpResponse class and using that you can access the status code as follows;

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.

Response httpResponse = client.newCall(request).execute(); 
httpResponse.code();
Ailis answered 1/6, 2014 at 14:8 Comment(2)
The execute-function returns an com.squareup.okhttp.Response-object, not an org.apache.http.HttpResponse objectCaceres
There is a method called code(square.github.io/okhttp/javadoc/com/squareup/okhttp/…) within the class you just mentioned. Are you not able to use that?Ailis
B
40

You can get response with:

Response response = client.newCall(request).execute();

And get response status code with:

int responseCode = response.code();
Bewilder answered 4/6, 2014 at 12:16 Comment(0)
D
0
Response response = client.newCall(request).execute();
HttpStatus status = response!=null ? HttpStatus.resolve(response.code()) : null;
Dr answered 17/1, 2023 at 6:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.