美文网首页Android技术分享
Android Retrofit 解决response.body

Android Retrofit 解决response.body

作者: 杨南北 | 来源:发表于2022-04-20 11:02 被阅读0次

Retrofit 请求结果响应数据 response.body().string() 调用一次之后再掉第二次显示结果为空值
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Debug.d("response:"+response.body().string());
ResponseEntity responseEntity = ResponseWrapper.getResponseEntity(response.body().string());
if (MSG_CODE_SUCCESS == responseEntity.getCode()) {
getView().modifyOrderDataSuccess();
} else
getView().modifyOrderDataFail(responseEntity.getMessage());
getView().showContent();
} catch (Exception e) {
e.printStackTrace();
}
}
如上代码,我在Debug打印调用了一次response.body().string(),后面在进行结构体解析时就出现response.body().string()的值为空,查看了一下string()方法

public final String string() throws IOException {
BufferedSource source = this.source();

    String var3;
    try {
        Charset charset = Util.bomAwareCharset(source, this.charset());
        var3 = source.readString(charset);
    } finally {
        Util.closeQuietly(source);
    }

    return var3;
}

Util.closeQuietly(source);最后关闭了缓存数据,也就是说response.body().string()调用一次后就被清掉了,但是我们有的时候确实需要调用两次,应该怎么处理了,解决方式如下
ResponseBody responseBody = response.body();
//解决response.body().string();只能打印一次
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.getBuffer();
Charset UTF8 = Charset.forName("UTF-8");
String string = buffer.clone().readString(UTF8);
这样就能完美解决了。

相关文章

网友评论

    本文标题:Android Retrofit 解决response.body

    本文链接:https://www.haomeiwen.com/subject/rcxeertx.html