Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Http Status Code with OkHttp

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?

like image 508
maja Avatar asked Jun 01 '14 13:06

maja


People also ask

What is a HTTP 200 response?

The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET : The resource has been fetched and is transmitted in the message body.

Should post return 200 or 201?

The 200 status code is by far the most common returned. It means, simply, that the request was received and understood and is being processed. A 201 status code indicates that a request was successful and as a result, a resource has been created (for example a new page).


1 Answers

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(); 
like image 87
dinukadev Avatar answered Sep 18 '22 17:09

dinukadev