[英]Java : Android : Retrofit 2 response code is 200, response.body is null
[英]Retrofit call.enqueue code 200, but response.body() is empty
我從API的 response.body()
獲取JSON
時遇到問題。
Logcat顯示請求成功,但是當我要將主體復制到模型對象時,它為null。
我已經只將JSON
縮短為一個鍵和一個值(logcat的結尾),但是即使這樣我也無法讀取響應。
Logcat:
D/OkHttp: <-- 200 http://10.0.2.2:8080/groups?page=1&limit=25 (33ms)
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 14 Jan 2019 19:31:10 GMT
D/OkHttp: [{"name":"Delfiny"}]
<-- END HTTP (20-byte body)
型號類別:
public class GroupsResponseModel {
@SerializedName("name")
@Expose
private String name;
public GroupsResponseModel() {
}
public GroupsResponseModel(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Api接口:
@GET("groups")
Call<GroupsResponseModel> getGroups(@Query("page") int page,
@Query("limit") int limit);
改造和攔截器:
public static Retrofit getClient()
{
HttpLoggingInterceptor interceptor = new
HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient().newBuilder().
addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws
IOException {
Request originalRequest = chain.request();
Request.Builder builder = originalRequest.newBuilder().header(Utils.getAuthKey(),
Utils.getAuthValue());
Request newRequest = builder.build();
return chain.proceed(newRequest);
}
})
.addInterceptor(interceptor)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(Utils.getURL())
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
呼叫入隊:
Call<GroupsResponseModel> call = apiInterface.getGroups(1, 25);
call.enqueue(new Callback<GroupsResponseModel>() {
@Override
public void onResponse(Call<GroupsResponseModel> call, Response<GroupsResponseModel> response) {
groupsResponseModel = response.body();
Toast.makeText(GroupActivity.this, "response: " + groupsResponseModel.getName(), Toast.LENGTH_LONG).show();
//groups = new ArrayList<>(Arrays.asList(groupsResponseModel.getName()));
groupAdapter = new GroupAdapter(groups);
recyclerView.setAdapter(groupAdapter);
}
@Override
public void onFailure(Call<GroupsResponseModel> call, Throwable t) {
}
});
預期結果需要解析。
如果您完全確定服務器會發送正確的json,請檢查您的pojo類。 首先刪除@Exposed注解
我建議您使用Profiler之類的Android Studio調試工具監視可在Profiler的“網絡”部分輕松訪問的網絡(API調用)請求和響應主體,請查看以下鏈接: Android Profiler
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.