Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does OkHttp get Json string?

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?

like image 808
Haifeng Zhang Avatar asked Jan 29 '15 18:01

Haifeng Zhang


People also ask

How do I get JSON from OkHttp response?

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.

What is OkHttp in Java?

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.


2 Answers

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);            
like image 112
Newbies Avatar answered Oct 03 '22 10:10

Newbies


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

like image 29
Venkat Veeravalli Avatar answered Oct 03 '22 11:10

Venkat Veeravalli