我正在尝试使用OkHttp获取一些json数据,但不知道为什么当我尝试记录response.body().toString()
时,我得到的是Results:﹕ com.squareup.okhttp.Call$RealResponseBody@41c16aa8
try {
URL url = new URL(BaseUrl);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.header(/****/)
.build();
Call call = client.newCall(request);
Response response = call.execute();
**//for some reason this successfully prints out the response**
System.out.println("YEAH: " + response.body().string());
if(!response.isSuccessful()) {
Log.i("Response code", " " + response.code());
}
Log.i("Response code", response.code() + " ");
String results = response.body().toString();
Log.i("OkHTTP Results: ", results);
我不知道我做错了什么。如何获得响应字符串?
发布于 2015-08-31 09:21:51
以防有人碰到和我一样的怪事。我在调试模式的开发过程中运行我的代码,显然是从OKHttp 2.4开始。
..the响应体是一个可能只消耗一次的一次性值。
因此,在调试过程中,有一个来自检查人员的“幕后”调用,而主体始终是空的。请参阅:https://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html
发布于 2015-02-03 13:52:13
您必须使用.string()
函数在System.out.println()
中打印响应。但在Log.i()
中,您最终使用的是.toString()
。
因此,请在响应体上使用.string()
打印和获取请求的响应,例如:
response.body().string();
注:
.toString()
:这将以字符串格式返回对象。.string()
:这将返回您的响应。我认为这解决了你的问题..。正确的。
发布于 2018-02-20 07:28:29
response.body.string()
只能消耗一次。请按以下方式使用:
String responseBodyString = response.body.string();
在应用程序中根据需要使用responseBodyString。
https://stackoverflow.com/questions/28300359
复制相似问题