TooManyEduardos TooManyEduardos - 6 months ago 104
Android Question

Retrofit2 onFailure not called for error 401

I'm making a network call to login to a service, and if you pass an invalid login, the Call object from retrofit2 still calls

onResponse
but never
onFailure
.

Even in
onResponse
I can call
response.code()
and the returning code is 401, as expected.

Any idea of what I'm doing wrong?

Here's my code for the activity that starts everything:

Call<Login> call = LoginUtils.loginUser(ServiceUtils.getRequestHeaders(LoginActivity.this),
BuildConfig.ORDER_SERVICE_DOMAIN, uname, pass);
call.enqueue(new retrofit2.Callback<Login>() {
@Override
public void onResponse(Call<Login> call, retrofit2.Response<Login> response) {
System.out.println("onResponse");
System.out.println("responseCode = " + response.code());
}

@Override
public void onFailure(Call<Login> call, Throwable t) {
System.out.println("onFailure");

}
});


Here's how we're setting up the Service layer:

public LoginService(final String domain, final Map<String, String> headers) {

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(CONNECT_TIMEOUT_SECS, TimeUnit.SECONDS)
.writeTimeout(READ_TIMEOUT_SECS, TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT_SECS, TimeUnit.SECONDS)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder request = original.newBuilder();
if (!headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
}
request.method(original.method(), original.body());
return chain.proceed(request.build());
}
})
.addInterceptor(loggingInterceptor)
.build();

// create the rest adapter
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(GSON))
.baseUrl(domain)
.client(httpClient)
.build();

loginServices = retrofit.create(LoginServices.class);
}


And finally, here's our interface:

@GET
Call<Login> getLoginCustompath(@Url String url,
@Header("Authorization") String authorization);


What am I not seeing here?

Thank you for your help.

Answer

The 401 code means "Unautorized", there is no error in the comunication and that is why onFaliure was not called.

The server is responding you that your user or password are wrong.

Hope it helps.

Comments