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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28300359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:58:14  来源:igfitidea点击:

Can't get OkHttp's response.body.toString() to return a string

javaandroidokhttp

提问by freddieptf

I'm trying to get some json data using OkHttp and can't figure out why when i try logging the response.body().toString()what i get is Results:﹕ com.squareup.okhttp.Call$RealResponseBody@41c16aa8

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

Log

日志

I don't know what i'm doing wrong here. How do i get the response string?

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

采纳答案by V.J.

You have use .string()function to print the response in System.out.println(). But at last in Log.i()you are using .toString().

您可以使用.string()函数在System.out.println(). 但最后Log.i()你正在使用.toString().

So please use .string()on response body to print and get your request's response, like:

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

response.body().string();

NOTE:

笔记:

  1. .toString(): This returns your object in string format.

  2. .string(): This returns your response.

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

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

I think this solve your problem... Right.

我认为这解决了你的问题......对。

回答by Oded Regev

Just in case someone bumps into the same weird thing as I have. I run my code during development in Debug Modeand apparently since OKHttp 2.4

以防万一有人遇到和我一样奇怪的事情。我在调试模式的开发过程中运行我的代码,显然是从 OKHttp 2.4

..the response body is a one-shot value that may be consumed only once

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

So when in debug there is a call "behind the scene" from the inspector and the body is always empty. See: https://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html

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

回答by Nethaji Narasimalu

The response.body,.string()can be consumed only once. Please use as below:

response.body,.string()可一次食用。请按如下方式使用:

String responseBodyString = response.body.string();
use the responseBodyString as needed in your application.

回答by Aoun allah Billel

try to change it like that for example:

尝试像这样改变它,例如:

protected String doInBackground(String... params) {
            try {
                JSONObject root = new JSONObject();
                JSONObject data = new JSONObject();
                data.put("type", type);
                data.put("message", message);
                data.put("title", title);
                data.put("image_url", imageUrl);
                data.put("uid",uid);
                data.put("id", id);
                data.put("message_id", messageId);
                data.put("display_name", displayName);
                root.put("data", data);
                root.put("registration_ids", new JSONArray(receipts));
                RequestBody body = RequestBody.create(JSON, root.toString());
                Request request = new Request.Builder()
                        .url(URL)
                        .post(body)
                        .addHeader("Authorization", "key=" + serverKey)
                        .build();
                Response response = mClient.newCall(request).execute();
                String result = response.body().string();
                Log.d(TAG, "Result: " + result);
                return result;
            } catch (Exception ex) {
                Log.e(TAG,"Exception -> "+ex.getMessage());
            }
            return null;
        }