Retrofit response

Let’s have a look at a theoretical introduction to Retrofit before we move on to coding.

For a more complete and in-depth explanation, check out our complete Retrofit course

In this article we will have a look at the response we get back from the api endpoint and we will see how we can either get content from that response, get the status or other useful information.

The response object is what you get back when you perform a request. It really depends on the type of request that you make whether you get the response instantly or you perform an asynchronous operation that allows you to do that in the background and get that response at a later time. Regardless, you do get a response object. What can we do with that object?

We have a few different options. I’m going to list most of these options in this article, and then we’re going to go into our code and try out one or two of these. I’m going to leave it to you as an exercise to practice all the other options.

Was the request successful


That is simply a flag that the response has that indicates whether this request returned a 200 OK or an error. That is useful when you simply want to do an IF check to tell whether you have a successful response or not

Get the response contents


The response contents is simply the information that is returned from the backend server. You can get this in different forms, for example in our application we convert that response through GSON into an object that we can use.

Get the response code


The code is the HTTP code that was returned from the api. So it might be 200 if the request has been completed successfully, or it might be an error code, for example 404 if the resource is not found. So you can make a decision based on that response code.

Get the HTTP message


This will return the message part of the HTTP response. If your request was successful, the message would be OK, if you get an error, the response would be the message of that error.

Get the headers


Retrofit headers

This returns all the headers received from the backend api with the response. These are usually the headers that you provide with the request, but the server can also add its own headers to the response and provide them here.

Get the error message


If the request has resulted in an error you can get the message this way. This will be empty if the request was successful.

Get the raw text


Finally we can get the raw text of the response. If for instance you receive an html response you might want to navigate it manually (programmatically) then you would use the raw response to get that information and process it in code yourself rather than have a converter do the work for you.

For a more complete and in-depth explanation, check out our complete Retrofit course

Close Bitnami banner