Retrofit2 onFailure 未调用错误 401

Retrofit2 onFailure not called for error 401

我正在进行网络调用以登录服务,如果您传递了无效的登录信息,retrofit2 中的 Call 对象仍会调用 onResponse 但不会调用 onFailure.

即使在 onResponse 中,我也可以调用 response.code() 并且返回代码是 401,正如预期的那样。

知道我做错了什么吗?

这是我的 activity 启动所有内容的代码:

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");

    }
});

以下是我们设置服务层的方式:

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);
}

最后,这是我们的界面:

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

我在这里没有看到什么?

感谢您的帮助。

401 code 表示“Unautorized”,通信没有错误,这就是为什么 onFaliure 没有被调用的原因。

服务器正在回复您,您的用户名或密码错误。

希望对您有所帮助。

来自 Retrofit2 的源代码:

/**
   * Invoked when a network exception occurred talking to the server or when an unexpected
   * exception occurred creating the request or processing the response.
   */
  void onFailure(Call<T> call, Throwable t);

HTTP 401 表示 Unauthorized 因此您有一个有效的请求但凭据无效。

参考:Retrofit2 Source code