TooManyEduardos TooManyEduardos - 2 years ago 407
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

but never

Even in
I can call
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>() {
public void onResponse(Call<Login> call, retrofit2.Response<Login> response) {
System.out.println("responseCode = " + response.code());

public void onFailure(Call<Login> call, Throwable t) {


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

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

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();

OkHttpClient httpClient = new OkHttpClient.Builder()
.writeTimeout(READ_TIMEOUT_SECS, TimeUnit.SECONDS)
.addInterceptor(new Interceptor() {
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(;

// create the rest adapter
Retrofit retrofit = new Retrofit.Builder()

loginServices = retrofit.create(LoginServices.class);

And finally, here's our interface:

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

What am I not seeing here?

Thank you for your help.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download