关于java:无法获取OkHttp \\的response.body.toString()返回字符串

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

我正在尝试使用OkHttp获取一些json数据,无法弄清楚为什么当我尝试记录response.body().toString()时得到的是Results:﹕ com.squareup.okhttp.Call$RealResponseBody@41c16aa8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

我不知道我在做什么错。如何获取响应字符串?


您已使用.string()功能在System.out.println()中打印响应。但是最后在Log.i()中,您正在使用.toString()

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

1
response.body().string();

注意:

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

  • .string():这将返回您的响应。

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


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

    开始

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

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


    response.body,.string()只能使用一次。
    请按以下方式使用:

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


    以下是我修改过的CurlInterceptor。在使用旧的Response之后,请检查在我要重新创建Response对象的拦截函数的末尾。

    var responseBodyString = responseBody?.string()

    response = response.newBuilder()
    .body(
    ResponseBody.create(
    responseBody?.contentType(),
    responseBodyString.toByteArray()
    )
    )
    .build()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    class CurlInterceptor: Interceptor
    {

        var gson = GsonBuilder().setPrettyPrinting().create()

        override fun intercept(chain: Interceptor.Chain): Response {

        Timber.d(" **** ->>Request to server -> ****")

        val request = chain.request()
        var response = chain.proceed(request)

        var curl ="curl -v -X  ${request.method()}"

        val headers = request.headers()

        for ( i in 0..(headers.size() -1) ){
            curl ="${curl} -H "${headers.name(i)}: ${headers.value(i)}""
        }

        val requestBody = request.body()
        if (requestBody != null) {
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            var charset: Charset =
                Charset.forName("UTF-8")
            curl ="${curl} --data '${buffer.readString(charset).replace("\
    ","\\\
    ")}'"
        }

        Timber.d("$curl ${request.url()}")
        Timber.d("response status code ${response.code()} message: ${response.message()}")

       
        dumbHeaders(response)

        var responseBody = response?.body()

        if(responseBody != null )
        {
            var responseBodyString = responseBody?.string()

                response = response.newBuilder()
                    .body(
                        ResponseBody.create(
                            responseBody?.contentType(),
                            responseBodyString.toByteArray()
                        )
                    )
                    .build()


            responseBodyString = gson.toJson(responseBodyString)

            Timber.d("response json -> \
     $responseBodyString"
    )

        }

        Timber.d(" **** << Response from server ****")

        return response
    }



    fun dumbHeaders(response: Response) {
        try {
            if (response.headers() != null) {

                for (headerName in response.headers().names()) {
                    for (headerValue in response.headers(headerName)) {
                        Timber.d("Header $headerName : $headerValue")
                    }
                }
            }
        }
    catch (ex: Exception){}
    }
    }

    使用字符串后重新创建响应对象

    val responseBodyString = response.body()!!。string()

    响应= response.newBuilder()
    .body(ResponseBody.create(responseBody?.contentType(),responseBodyString.toByteArray()))
    .build()


    鉴于在大文件的情况下响应可能会产生OutOfMemoryError,您可以改为用字节数"窥视"正文并调用string()方法。

    请注意,这会消耗身体。

    response.peekBody(500).string());


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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    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;
            }