okhttp通过response.body().string() 获取字符串类型的responsebody
源码分析
| public final String string() throws IOException { try (BufferedSource source = source()) { Charset charset = Util.bomAwareCharset(source, charset()); return source.readString(charset); } }
@Override public void close() { Util.closeQuietly(source()); }
|
ResponseBody,其实现了 Closeable
接口,通过复写 close()
方法来 关闭并释放资源,关闭 ResponseBody
子类所持有的 BufferedSource
接口对象,当我们第一次调用 response.body().string()
时,OkHttp 将响应体的缓冲资源返回的同时,调用 closeQuietly()
方法默默释放了资源
获取responseBody
1 2 3 4 5 6 7
| private static String getResponseBody(Response response) throws IOException { BufferedSource source = response.body().source(); source.request(Long.MAX_VALUE); Buffer buffer = source.getBuffer(); String responseBody = buffer.clone().readUtf8(); return responseBody; }
|
获取requestBody
1 2 3 4 5 6 7 8
| private static String getRequestBody(Request request) throws IOException { Buffer buffer = new Buffer(); if (request.body() != null) { request.body().writeTo(buffer); return buffer.clone().readUtf8(); } return ""; }
|