Log.d(TAG, "onResponse: " + responseStr);
}
//解析请求体
parseReponseStr(responseStr);
}
});
3.结合源码分析问题
问题解决了,事后还是要分析的。由于之前对 OkHttp
的了解仅限于使用,没有仔细分析过其内部实现的细节,周末抽时间往下看了看,算是弄明白了问题发生的原因。
先分析最直观的问题:为何 response.body().string()
只能调用一次?
拆解来看,先通过 response.body()
得到 ResponseBody
对象(其是一个抽象类,在此我们不需要关心具体的实现类),然后调用 ResponseBody
的 string()
方法得到响应体的内容。
分析后 body()
方法没有问题,我们往下看 string()
方法:
public final String string() throws IOException {
return new String(bytes(), charset().name());
}
很简单,通过指定字符集(charset)将 byte()
方法返回的 byte[]
数组转为 String
对象,构造没有问题,继续往下看 byte()
方法:
public final byte[] bytes() throws IOException {
//…
BufferedSource source = source();
byte[] bytes;
try {
bytes = source.readByteArray();
} finally {
Util.closeQuietly(source);
}
//…
return bytes;
}
//...
表示删减了无关代码,下同。
在 byte()
方法中,通过 BufferedSource
接口对象读取 byte[]
数组并返回。结合上面提到的异常,我注