我从我的 API 的JSON
获取response.body()
时遇到问题。
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;
}
}
ApiInterface:
@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) {
}
});
需要分析预期的结果。
答案 0 :(得分:0)
如果您完全确定服务器发送了正确的json,请检查您的pojo类。首先删除@Exposed注释
答案 1 :(得分:0)
我建议您使用Profiler之类的Android Studio调试工具来监视可在Profiler的“网络”部分轻松访问的网络(API调用)请求和响应正文,请查看以下链接:Profiler Android