Marc Marc - 10 months ago 100
Android Question

Retrofit connection failure returns RetrofitError.response as null

Using Retrofit 1.6.0, OkHTTP 2.0.0, and OkHTTP-UrlConnection 2.0.0.

I am doing a POST to a service using Retrofit to a URL that does not exist. The failure callback is called, as expected. However, the RetrofitError parameter does not have a response. I would really like to grab the HTTP status code that was returned by using


but since getResponse() returns null, I can't.

Why is getResponse() null and how can I get the status?


Also, the error I am receiving is UnknownHostException, as expected. Repeat: I am expecting this error. I want to know how to get the HTTP status code or why error.getResponse() returns null.

Edit: Here's some code:
RestAdapter restAdapter = new RestAdapter.Builder()
sService = restAdapter.create(ServiceInterface.class);
void login(@Body JsonObject body, Callback<String> callback);
public void failure(RetrofitError error) {
if (error.getResponse() == null) {

// error.getResponse() is null when I need to get the status code
// from it.


Answer Source

When you get an UnknownHostException it means, that you were not able to establish a connection to the server. You cannot, in fact, expect a HTTP status in that case.

Naturally you only get a Http response (and with that a status) when you can connect to a server.

Even when you get a 404 status code, you made a connection to the server. That is not the same as a UnknownHostException.

The getResponse() can return null if you didn't get a response.