简体   繁体   中英

Can't Log OKHTTP3 response.body.string

OK- so I'm a bit confused by this.

I've setup an OKHTTP3 POST. When I get the response I've been trying to put the body into a string (it's a string response) but something is going wonky:

try {
        Response response = client.newCall(request).execute();

        String rep = response.body().string();
        if(rep.length() > 0){
            Log.i(TAG, "Got Response");
            Log.i(TAG, rep);
        }

    }catch (Exception e){
        e.printStackTrace();
    }

I get a Log saying "Got Response" but (the length is 80) then it just stops. It doesn't say my rep string is null, or empty... It just never calls that second Log.

Anyone have any kind of idea what's up?

Try using this..

      OkHttpClient client = new OkHttpClient.Builder().build();          

      Request request = new Request.Builder()
            .url("")
            .build();

      client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {

                    Log.d("Response",response.body().string());

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    response.body().close();
                }
            }

        });

Right... So apparently I just needed to put the part that gets the string in an AsyncTask, and it started working.

There wasn't any error message or anything indicating to do so, but I went back and actually looked at the documentation for the Callback, and it mentions consuming the body on another thread.

new SendPictureClass().execute(response);

Probably should have started there to begin with... ¯_(ツ)_/¯

Thanks for the help guys!

I also met this problem, Log can't work.
And I found a temporary solution.
I try to use Toast to show the response, then I found that the response poped up, but with a lot of spaces(not sure if those characters are spaces).

So I am using Log.i(TAG, rep.trim()); , which works well. I don't know if this solution is good for this problem, but it works for me after all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM