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?


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);           

Decode an OkHttp JSON Response, readString(charset) instead. In this article, we're going to use string() since our response is small and we don't have memory or performance� In spite of these great features, OkHttp doesn't have a built-in encoder/decoder for JSON, XML, and other content types. However, we can implement these with the help of XML/JSON binding libraries, or we can use high-level libraries like Feign or Retrofit. To implement our JSON decoder, we need to extract the JSON from the result of the service call.


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

okhttp3.Response.body java code examples, public static void main(String args) throws Exception { OkHttpClient client = new OkHttpClient(); origin: square/okhttp. String post(String url, String json) throws IOException { RequestBody body This is not necessarily the same request i. Enter your email and we will send you instructions on how to reset your password


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.

Using the OkHttp library for HTTP requests - Tutorial, OkHTTP is an open source project designed to be an efficient HTTP MediaType.parse("application/json; charset=utf-8"); // test data String� il apparaît quand tapez l'url dans un navigateur, malheureusement il montre sorte d'adresse de mémoire autre que la chaîne json lorsque je demande avec Okhttp. TestActivity﹕ [email protected] Le Okhttp code Im en utilisant:


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'

Recipes - OkHttp, The string() method on response body is convenient and efficient for small documents. addHeader("Accept", "application/vnd.github.v3+json") .build() client. Download Demo from GitHub: JSON Parsing using okHttp. Hope You will enjoy with Android JSON Parsing with okHttp and basic of Android Design Library. Any question, Any query, Any suggestion Always Welcome. Do comment. Thank you.


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())
                }
            })

ResponseBody - OkHttp, bytes(); Response.body().string(). There is no benefit to invoking multiple close() methods for the same� So, back when I was using Koush's Ion, I was able to add a json body to my posts with a simple .setJsonObjectBody(json).asJsonObject(). I'm moving over to OkHttp, and I really don't see a good way to do that.


Java Code Examples for com.squareup.okhttp.Response, This page shows Java code examples of com.squareup.okhttp. values defined as part of the request matcher are what is expected to be set due to the users configuration. public byte[] postString(String url, String json) throws IOException� In this post, we will create an OkHttp GET HTTP request example in Java. OkHTTP is an open source project designed to be an efficient HTTP client for Android and Java applications. OkHttp supports Android 5.0+ (API level 21+) and Java 1.8+. In this article, we will write a code using Java 1.8+.


OkHttp Android Example Tutorial, The response string returned is of the JSON format that gets printed on the screen. You can try out other open� This is an example for the usage of OkHttp in a standard Java program, but this library can also be used in Android applications. This example demonstrates the usage of the API. Create a new Java project called com.vogella.java.library.okhttp.


How does OkHttp get Json string?, The right way is response.body().string() other than response.body.toString(). Im using Jetty servlet, the URL is http://172.16.10.126:8789/test/path/jsonpage� JSON is a simple string format data. JSON is readable format. It is very easy to read and infer information from it. JSON format is simple to use. JSON is quite light-weight compared to other formats like XML etc,. JSON format can be easily converted into Java objects in an Object oriented manner. JSON is interoperable: program and platform