我正在进行网络通话以登录服务,如果您通过无效登录,则retrofit2中的Call对象仍然会调用onResponse
但不会onFailure
。
即使在onResponse
我也可以调用response.code()
,返回的代码是401,正如预期的那样。
知道我做错了什么?
这是我开始所有活动的活动代码:
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);
我在这里看不到什么?
感谢您的帮助。
答案 0 :(得分:3)
来自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
,因此您拥有无效凭据的有效请求。
答案 1 :(得分:2)
401 code
表示“Unautorized
”,通讯中没有错误,这就是未调用onFaliure
的原因。
服务器正在回复您的用户或密码错误。
希望它有所帮助。