当我将response.body()转换为POJO类时,如何关闭response.body?
public class RetrofitClient {
private static Retrofit retrofit = null;
private final static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.build();
private final static Gson gson = new GsonBuilder().setLenient().create();
public static Retrofit getClient(String baseUrl) {
if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}}
public static class GroupMembersCallback implements Callback<GroupAdminPreview>{
private List<String> usersUsername = new ArrayList<>();
private List<String> usersFullName = new ArrayList<>();
private List<String> usersIsAdmin = new ArrayList<>();
private GroupMembersAdapter membersAdapter;
private WeakReference<RecyclerView> mRecyclerView;
private WeakReference<Context> contextWeakReference;
public GroupMembersCallback(WeakReference<RecyclerView> mRecyclerView, WeakReference<Context> context){
this.mRecyclerView = mRecyclerView;
contextWeakReference = context;
}
@Override
public void onResponse(Call<GroupAdminPreview> call, Response<GroupAdminPreview> response) {
GroupAdminPreview groupAdminPreview = response.body();
for (GroupAdminPreview.GroupUser groupUser : groupAdminPreview.getGroupUsers()){
usersUsername.add(groupUser.getUserName());
usersFullName.add(groupUser.getFirstName() + " " + groupUser.getLastName());
usersIsAdmin.add(groupUser.getIsAdmin());
}
membersAdapter = new GroupMembersAdapter(usersUsername, usersFullName, usersIsAdmin, contextWeakReference, mRecyclerView);
mRecyclerView.get().setAdapter(membersAdapter);
}
@Override
public void onFailure(Call<GroupAdminPreview> call, Throwable t) {
System.out.println(t);
}
}
我在阅读关于使用此代码后关闭response.body的内容:
ResponseBody body = response.body();
body.close();
但是当我使用POJO课程时,我无法做同样的事情。 对不起,我还是开发Android应用程序的初学者。
我的应用程序运行一段时间后,我在Android Monitor中得到了这个:
A connection to ....... was leaked. Did you forget to close a response body?
答案 0 :(得分:0)
事实上,如果使用Retrofit,您不需要关闭ResponseBody。转换器为你做了。
e.g。如果您使用JacksonConverterFactory,则会有名为JacksonResponseBodyConverter的类,请参阅下面的代码:
@Override public T convert(ResponseBody value) throws IOException {
try {
return adapter.readValue(value.charStream());
} finally {
value.close();
}
}
编辑: 尝试检查onResponse回调中的响应是否成功,如果响应不成功则调用response.errorBody.close()
答案 1 :(得分:0)
Okhttp和Retrofit使用冲突。或者查看这些库的旧版本。
Retrofit 2为您关闭ResponseBody