Marc Marc - 19 days ago 9
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

error.getResponse().getStatus()


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

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

Thanks.

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:

RestAdapterBuilderClass.java
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://badURL.DoesntMatter/");
.setRequestInterceptor(sRequestInterceptor)
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
sService = restAdapter.create(ServiceInterface.class);

ServiceInterface.java
@POST("/Login")
void login(@Body JsonObject body, Callback<String> callback);

CallbackClass.java
@Override
public void failure(RetrofitError error) {
if (error.getResponse() == null) {

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

return;
}
}

Answer

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.