【问题标题】:How to get the HTTP error code from a failed request in Retrofit 2.0.0?如何从 Retrofit 2.0.0 中的失败请求中获取 HTTP 错误代码?
【发布时间】:2015-09-17 18:00:59
【问题描述】:

我正在使用以下回调方法拨打电话:

Callback<PeopleList> callback = new Callback<PeopleList>() {
    @Override
    public void onResponse(Response<PeopleList> response) {
        Toast.makeText(LoginActivity.this,getString(R.string.login_failed), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Throwable t) {
        Toast.makeText(LoginActivity.this,getString(R.string.login_failed), Toast.LENGTH_SHORT).show();
    }
};

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://example.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
retrofit.create(MyService.class).getPeopleData().enqueue(callback);

到如下界面:

public interface MyService {

    @Headers("Accept: application/json")
    @GET("/data/people/")
    Call<PeopleList> getPeopleData();
}

这个回调在成功的请求上工作得很好。但是,在不成功的情况下,它并没有给我进一步调查的机会,因为 onFailure 方法不允许我检索响应附带的 http 错误代码。

在进一步调查中,我发现根据几个 stackoverflow 线程,即使请求不成功,也应该调用 onResponse 方法。然而,这似乎不仅与我的个人经验不一致,而且与回调接口的文档不一致,其中指出:

传达来自服务器的响应或离线请求。一种且只有一种方法将是 响应给定请求而调用。

那么问题来了,如果不调用 onResponse 方法,我如何从失败的响应中获取 HTTP 错误代码?

【问题讨论】:

  • 将调用两种方法之一。除了在onFailure 上敬酒,你能做一个t.printStackTrace() 吗?然后您可以查看您的 logcat 以了解错误的来源。

标签: android retrofit


【解决方案1】:

我认为即使有错误的响应也会调用 onResponse 方法,所以这样的事情可能会起作用(对不起,如果我做错了第一次尝试回答任何人:)

 @Override
public void onResponse(Response<PeopleList> response) {
    if(response.isSuccess()){ //good http request, do something with response.body()....
         Toast.makeText(LoginActivity.this,getString(R.string.login_failed), Toast.LENGTH_SHORT).show();
    } else { //bad http response do something with error message
        try {
            Toast.makeText(LoginActivity.this,response.errorBody().string().toString(), Toast.LENGTH_SHORT).show();
        } catch (IOException e){
            //IOException caught from response.errorBody().string() method
        }
    }
}

【讨论】:

    【解决方案2】:

    onResponse() 将始终被调用,对于失败的请求 .body() 为空。 response.isSuccess()用于快速区分http代码在200到300之间的请求。

    如果您想访问 http 代码,您可以执行以下操作:

    int htppResultCode = response.raw().code();

    它访问原始的Response 对象,该对象包含有关请求的一般结果的信息。

    【讨论】:

      猜你喜欢
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 2013-10-23
      • 1970-01-01
      • 2015-04-10
      • 2020-03-29
      • 2021-03-29
      相关资源
      最近更新 更多