无法让 OkHttp 的 response.body.toString() 返回一个字符串

新手上路,请多包涵

我正在尝试使用 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);

日志

我不知道我在这里做错了什么。我如何获得响应字符串?

原文由 freddieptf 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

以防万一有人碰到和我一样奇怪的东西。我在 调试模式下 的开发过程中运行我的代码,显然是因为 OKHttp 2.4

..响应体是一个一次性值,只能被消耗一次

因此,在调试时,检查员会在“幕后”进行调用,并且主体始终是空的。请参阅: https ://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html

原文由 Oded Regev 发布,翻译遵循 CC BY-SA 3.0 许可协议

您已使用 .string() 函数在 System.out.println() 中打印响应。但最后在 Log.i() 你正在使用 .toString()

因此,请在响应正文中使用 .string() 打印并获取您的请求响应,例如:

 response.body().string();

笔记:

  1. .toString() :这将以字符串格式返回您的对象。

  2. .string() :这将返回您的回复。

我认为这可以解决您的问题…对。

原文由 V.J. 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题