【问题标题】:Response.body() returns an object with null properties while using Retrofit 2.0Response.body() 在使用 Retrofit 2.0 时返回一个具有空属性的对象
【发布时间】:2020-04-14 08:37:56
【问题描述】:

request 说的是 200 响应,但响应正文中的所有内容都是空的,我对改造是新的。谢谢

这是我的请求

Retrofit retrofit = new Retrofit.Builder().baseUrl(getString(R.string.FEED_BASE_URL))
            .addConverterFactory(GsonConverterFactory.create()).build();
    feed_api api = retrofit.create(feed_api.class);
    Map<String, String> feilds = new HashMap<>();
    feilds.put("param1",FEED_PROFILE_ID);
    feilds.put("param2",FEED_TOKEN);
    feilds.put("param3",decencrypted_id);

    retrofit2.Call<feed_model> call = api.get_single_post(feilds);
    call.enqueue(new retrofit2.Callback<feed_model>() {
     @Override
     public void onResponse(retrofit2.Call<feed_model> call, Response<feed_model> response) {
         if(response.isSuccessful()){
             if(response.body()!=null)
             feed_list.add(response.body());
             else
                 Toast.makeText(single_post_screen.this, "This post don't exist any more", Toast.LENGTH_SHORT).show();
         }
         social_adapter.notifyDataSetChanged();
     }

     @Override
     public void onFailure(retrofit2.Call<feed_model> call, Throwable t) {
         Log.d("eeeeeeeeeeeeeeeeeee",t.getMessage());
     }
 });

这是我的api函数

@FormUrlEncoded
@POST("my_url/")
@Headers({
        "Content-Type: application/json;charset=utf-8",
        "Accept: application/json;charset=utf-8",
        "Cache-Control: max-age=640000"
})
Call<feed_model> get_single_post(@FieldMap Map<String,String> fields);

【问题讨论】:

  • code 200 表示请求成功。如果您的 response.body 为 null,则表示服务器未返回任何正文

标签: android retrofit2


【解决方案1】:

你能添加一个日志拦截器来检查服务器是否真的返回了一个不为空的正文吗?

为此,请将改造初始化代码更改为:

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getString(R.string.FEED_BASE_URL))
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient.Builder().addInterceptor(new HttpLoggingInterceptor()).build())
.build();

您应该会在 Android Studio 的 logcat 日志中看到您的网络请求。

【讨论】:

  • 它说 java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
猜你喜欢
  • 2016-11-26
  • 2016-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 2019-05-18
  • 1970-01-01
相关资源
最近更新 更多