3 回答

TA贡献1828条经验 获得超4个赞
response.body().string() → 您只能调用 string() 一次。
由于响应正文可能很大,因此 OkHttp 不会将其存储在内存中,而是在您需要时将其作为流从网络读取。
当您将正文作为 string() 读取时,OkHttp 将下载响应正文并将其返回给您,而不保留对字符串的引用,如果没有新请求,则无法下载两次。
您不止一次地调用它。
try(..){
System.out.println(response.body().string());// once
return response.body().string();`// twice
}
您可以通过调用一次将响应保存在变量中,然后使用该变量进行进一步使用。
try(..){
String responseData = response.body().string();//Be cautious about memory constraint here.
System.out.println(responseData);
return responseData;`
}

TA贡献1890条经验 获得超9个赞
发生这种情况是因为.string()
只能调用一次
您可以通过以下方式解决该问题(Java):
ResponseBody responseBodyCopy = response.peekBody(Long.MAX_VALUE); responseBodyCopy.string();
通过复制响应正文,您可以避免使用.string()
两次

TA贡献1825条经验 获得超6个赞
也许你正在像这样的拦截器中关闭你的响应
override fun intercept(chain: Interceptor.Chain): Response {
//...
val response = chain.proceed(builder.build())
response.close()
//...
}
添加回答
举报