【问题标题】:Retrofit: Raw response body from a gson converted body改造:来自 gson 转换体的原始响应体
【发布时间】:2020-01-22 13:24:52
【问题描述】:

我正在使用以下库进行改造。

'com.squareup.retrofit2:retrofit:2.5.0'
'com.squareup.okhttp:okhttp:2.7.5'
'com.squareup.retrofit2:converter-gson:2.5.0'
'com.squareup.okhttp3:logging-interceptor:3.10.0'

如何在 onResponse 回调中获取原始响应?我已经搜索过它并得到了很多现在没有帮助的解决方案。我尝试了response.raw().body.string()response.body().source().toString(),它们会抛出无法从转换后的正文中读取正文。我也尝试过response.body().string(),但在这种情况下.string() 未解决。我可以使用拦截器记录响应,但我需要在我的onResponse() 回调中获得该响应,而不仅仅是在 logcat 中打印。 我的改造客户:

public static ApiService getClient(Context context) {

    if (retrofit == null) {
        if (BuildConfig.FLAVOR.equalsIgnoreCase("dev")){
            retrofit = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .build();
        }else {
            retrofit = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .client(SelfSigningClientBuilder.createClient(context))
                    .build();
        }

    }
    return retrofit.create(ApiService.class);
}

我的 Retyrofit 界面:

@retrofit2.http.POST("weekly_driver_earning_report/")
@retrofit2.http.FormUrlEncoded
Call<List<DailyEarnings>> getDriverWeeklyEarnings(@retrofit2.http.Field("access_token") String access_token, @retrofit2.http.Field("start_date") String start_date, @retrofit2.http.Field("end_date") String end_date);

【问题讨论】:

  • 发布您的改造界面。此外,使用一致的库版本。改造 2.5.0 依赖 okhttp > 3.0
  • 我认为必须删除 ORM 自动映射才能在其中获取 Call&lt;ResponseBody&gt;
  • 您必须将Call&lt;List&lt;DailyEarnings&gt;&gt; 更改为Call&lt;ResponseBody&gt; 才能在回调中获得整个http 响应。
  • 请也输入错误。如果您的 json 响应未经过验证,GsonConverterFactory 将无法反序列化,而是使用标量转换器工厂进行改造以打印原始响应。

标签: android gson retrofit okhttp interceptor


【解决方案1】:

按照this,我后来解决了我的问题。我将我的调用类型定义为特定的模型类,这就是为什么 response.body().string() 无法访问,将我的调用类型从 List 更改为 ResponseBody,我可以访问 response.body().string()。

【讨论】:

    猜你喜欢
    • 2016-09-28
    • 2018-11-04
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多