简体   繁体   中英

okhttp android not returning proper response body

Below is the okhttp part my code

                    StringBuilder finalQuery = new StringBuilder(fq);
                    finalQuery.deleteCharAt(finalQuery.length()-1);
                    //System.out.println("Final search query : "+finalQuery.toString());

                    Request request = new Request.Builder().url(finalQuery.toString()).build();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            System.out.println("FAILED!!!");
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if(response.isSuccessful())
                            {
                                StringBuilder strResponse = new StringBuilder(response.body().toString());
                                System.out.println("strResponse: "+strResponse.toString());
                                resp=strResponse.toString();
                                Intent intent = new Intent(MainActivity.this, onResponse.class);
                                startActivity(intent);
                            }
                            else
                            {
                                System.out.println("NOT SUCCESSFUL");
                            }

                        }
                    });

None of the strings are empty. The call to the website was successful, but the response is body is like this:

2020-05-05 13:47:40.982 15129-15161/com.example.lyricsapp I/System.out: strResponse: okhttp3.internal.http.RealResponseBody@b650836

When I used an online client to check for response using the same string, it was fine there. In my code, it isn't. What seems to be the error in my code?

Use string() to retrieve the response body content as a string. That is, replace

response.body().toString()

with

response.body().string()

toString() is the method from Object and it just gives you the class name and hash code.

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