无法通过OkHttp的response.body.toString()来返回字符串

时间:2015-02-03 13:41:11

标签: java android okhttp

我试图使用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

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

7 个答案:

答案 0 :(得分:182)

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

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

response.body().string();

注意:

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

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

  3. 我认为这可以解决你的问题......对。

答案 1 :(得分:23)

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

开始
  

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

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

答案 2 :(得分:6)

response.body,.string()只能消耗一次。 请使用如下:

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

答案 3 :(得分:1)

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

var responseBodyString = responseBody?.string()

response = response.newBuilder() 。身体( ResponseBody.create( responseBody?.contentType(), responseBodyString.toByteArray() ) ) .build()

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("\n", "\\n")}'"
    }

    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 -> \n $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){}
}
}

答案 4 :(得分:0)

例如尝试更改它:

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;
        }

答案 5 :(得分:0)

鉴于文件很大,响应可能会产生OutOfMemoryError,因此您可以用字节数“窥视”正文并调用string()方法。

请注意,这会消耗身体。

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

答案 6 :(得分:0)

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

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

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