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?
OkHttp Response To implement our JSON decoder, we need to extract the JSON from the result of the service call. For this, we can access the body via the body() method of the Response object.
OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With