77

Solution: It was a mistake on my side.

The right way is response.body().string() other than response.body.toString()

Im using Jetty servlet, the URL ishttp://172.16.10.126:8789/test/path/jsonpage, every time request this URL it will return

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

It shows up when type the url into a browser, unfortunately it shows kind of memory address other than the json string when I request with Okhttp.

TestActivity﹕ com.squareup.okhttp.internal.http.RealResponseBody@537a7f84

The Okhttp code Im using:

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

Can anyone helpe?

ardila
  • 1,277
  • 1
  • 13
  • 24
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125

6 Answers6

137
try {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
        .url(urls[0])
        .build();
    Response responses = null;

    try {
        responses = client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String jsonData = responses.body().string();
    JSONObject Jobject = new JSONObject(jsonData);
    JSONArray Jarray = Jobject.getJSONArray("employees");

    for (int i = 0; i < Jarray.length(); i++) {
        JSONObject object     = Jarray.getJSONObject(i);
    }
}

Example add to your columns:

JCol employees  = new employees();
colums.Setid(object.getInt("firstName"));
columnlist.add(lastName);           
gfullam
  • 11,531
  • 5
  • 50
  • 64
Newbies
  • 1,394
  • 1
  • 11
  • 3
  • 8
    I'm now getting the exception: `org.json.JSONException: Value okhttp3.internal.http.RealResponseBody@aeb56f3 of type java.lang.String cannot be converted to JSONObject` – Gokul NC Mar 18 '17 at 17:18
  • 23
    very easy mistake is to confuse `.string()` with '.toString()' – Zapnologica Jul 11 '17 at 12:42
  • 10
    You should specify where you get the objects from, like the JSONObject. please, Include the imports too. – Diego Alves Jan 15 '18 at 16:38
  • I'm trying to do simple request using Okhttp (3.x.x), is this the basic for request? – RoCkDevstack Apr 27 '18 at 06:50
  • `responses.body().string()` can be called just one time
    use this code directlty : `//String jsonData = responses.body().string(); JSONObject Jobject = new JSONObject(responses.body().string());`
    – Chakib Temal Oct 22 '20 at 20:05
  • how can we get multiple fields as objects. Eg - can we get another field like employees? – Manodhya Opallage Sep 26 '21 at 15:10
27

I am also faced the same issue

use this code:

// notice string() call
String resStr = response.body().string();    
JSONObject json = new JSONObject(resStr);

it definitely works

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
23

As I observed in my code. If once the value is fetched of body from Response, its become blank.

String str = response.body().string();  // {response:[]}

String str1  = response.body().string();  // BLANK

So I believe after fetching once the value from body, it become empty.

Suggestion : Store it in String, that can be used many time.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Kuldip Sharma
  • 782
  • 1
  • 6
  • 8
  • 1
    Thank you so much. Been trying to figure out this for a while and none of the above answers actually helped because I was first logging whole body and then trying to get the string and this was actually the issue. – Saad Ismail Jul 17 '18 at 12:47
9

I hope you managed to obtain the json data from the json string.

Well I think this will be of help

try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url(urls[0])
    .build();
Response responses = null;

try {
    responses = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}   

String jsonData = responses.body().string();

JSONObject Jobject = new JSONObject(jsonData);
JSONArray Jarray = Jobject.getJSONArray("employees");

//define the strings that will temporary store the data
String fname,lname;

//get the length of the json array
int limit = Jarray.length()

//datastore array of size limit
String dataStore[] = new String[limit];

for (int i = 0; i < limit; i++) {
    JSONObject object     = Jarray.getJSONObject(i);

    fname = object.getString("firstName");
    lname = object.getString("lastName");

    Log.d("JSON DATA", fname + " ## " + lname);

    //store the data into the array
    dataStore[i] = fname + " ## " + lname;
}

//prove that the data was stored in the array      
 for (String content ; dataStore ) {
        Log.d("ARRAY CONTENT", content);
    }

Remember to use AsyncTask or SyncAdapter(IntentService), to prevent getting a NetworkOnMainThreadException

Also import the okhttp library in your build.gradle

compile 'com.squareup.okhttp:okhttp:2.4.0'

Phillip Kigenyi
  • 1,359
  • 14
  • 21
3

Below code is for getting data from online server using GET method and okHTTP library for android kotlin...

Log.e("Main",response.body!!.string())

in above line !! is the thing using which you can get the json from response body

val client = OkHttpClient()
            val request: Request = Request.Builder()
                .get()
                .url("http://172.16.10.126:8789/test/path/jsonpage")
                .addHeader("", "")
                .addHeader("", "")
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // Handle this
                    Log.e("Main","Try again latter!!!")
                }

                override fun onResponse(call: Call, response: Response) {
                    // Handle this
                    Log.e("Main",response.body!!.string())
                }
            })
Deven
  • 684
  • 7
  • 10
1

I would like to add one more observation. You can call .string() method only once. If you try to call it twice, it will give you illegal state exception.

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 22 '22 at 10:28