【问题标题】:Retrofit 2.0 OnFailure - Raw ResponseRetrofit 2.0 OnFailure - 原始响应
【发布时间】:2015-10-10 11:36:42
【问题描述】:

我正在使用 retrofit 调用 Web 服务并且改造失败,来自“Throwable”的消息正在给我

java.lang.IllegalStateException: 应为 BEGIN_OBJECT,但在第 1 行第 1 列路径 $

我假设这是因为 .Net Web 服务抛出错误而不返回 JSON。但为了证明这一点,我需要能够在onFailure 中看到原始响应。无论如何我可以做到这一点吗?

这是我正在使用的代码

public void userLoginRequestEvent(final AuthenticateUserEvent event) {

Call call = sApi.login(event.getUsername(), event.getPassword(), OS_TYPE, DeviceInfoUtils.getDeviceName());
call.enqueue(new Callback<LoggedInUser>() {
  @Override
  public void onResponse(Response<LoggedInUser> response, Retrofit retrofit) {
    // response.isSuccess() is true if the response code is 2xx

    if (response.isSuccess()) {
      LoggedInUser user = response.body();

      AppBus.getInstance()
              .post(new UserIsAuthenticatedEvent(user, event.getUsername(),
                      event.getPassword()));
    } else {
      int statusCode = response.code();

      // handle request errors yourself
    }
  }

  @Override
  public void onFailure(Throwable t) {
    // handle execution failures like no internet connectivity
    Log.d("ERROR", t.getMessage());
  }


});

【问题讨论】:

  • 尝试使用stackoverflow.com/questions/32514410/logging-with-retrofit-2的方法记录请求/响应
  • 请提供完整的stacktrace列表,以及api接口列表。您可以通过在 onFailure(Throwable t) 方法中添加 t.printStackTrace() 来打印完整的堆栈跟踪。没有注意到这个问题有多老。还是没有解决吗? :)
  • @КлаусШварц 它已通过第一条评论解决,但没有发布我可以接受的答案
  • @keno - 如果您想将其作为答案发布,我可以接受吗?
  • @Flexicoder 我对你的问题本身有点好奇,并在没有反应流的情况下对 retrofit2 的使用进行了小型研究(我更喜欢 rx 实现,并且对它更有经验)。在我看来,当前的 API 已经发生了变化,并且与 2015 年的 API 不同。我认为最好的选择是如果 keno 会发布答案并且您将其标记为已接受,或者您将自己回答您的问题。我评论这个老问题的唯一原因是它仍然没有答案并且有相当多的选票。谢谢。

标签: android retrofit


【解决方案1】:

您可以使用okhttp-logging-interceptor 中存在的日志拦截器。

Logging with Retrofit 2 中也可以找到一个很好的例子。

【讨论】:

    【解决方案2】:

    您的服务器答案只是一个字符串,而不是一个对象。使用Interceptor 查看您收到的回复。

    添加拦截器依赖

    compile 'com.squareup.okhttp3:logging-interceptor:3.4.0'
    

    然后将其添加到您的自定义OkHttp 客户端。

    OKHttp client = ....
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);
    
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("url")
            .client(client) // add custom OkHttp client
    

    您可以检查BASICHEADERSBODY。在您的情况下,您检查 BODY 以查看您发送的正文以及作为响应正文发送的服务器。

    【讨论】:

      猜你喜欢
      • 2016-09-02
      • 2016-01-21
      • 1970-01-01
      • 2018-01-12
      • 2016-06-06
      • 2019-10-26
      • 2015-12-15
      • 2016-07-02
      • 2016-04-23
      相关资源
      最近更新 更多