OkHttp 如何获取 Json 字符串?

How does OkHttp get Json string?

解决方法: 这是我这边的一个错误。

正确的方法是 response.body().string() 而不是 response.body.toString()

我正在使用 Jetty servlet,URL 是 http://172.16.10.126:8789/test/path/jsonpage,每次请求这个 URL 它都会 return

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

它在浏览器中输入 url 时显示,不幸的是,当我用 Okhttp 请求时,它显示的内存地址不同于 json 字符串。

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

我使用的 Okhttp 代码:

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

有人可以帮忙吗?

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

示例添加到您的列:

JCol employees  = new employees();
colums.Setid(object.getInt("firstName"));
columnlist.add(lastName);           

希望您能够从 json 字符串中获取 json 数据。

好吧,我认为这会有所帮助

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

记得使用 AsyncTask 或 SyncAdapter(IntentService),以防止出现 NetworkOnMainThreadException

同时在您的 build.gradle 中导入 okhttp 库

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

我也遇到了同样的问题

使用此代码:

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

绝对有效

正如我在代码中观察到的那样。 如果一旦从Response中获取了body的值,它就变成了空白。

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

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

所以我相信从 body 中获取一次值后,它就变成空的了。

建议:用String形式存储,可以多次使用

以下代码用于使用 android kotlin 的 GET 方法和 okHTTP 库从在线服务器获取数据...

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

在上一行!!是你可以从响应正文

中获取json的东西
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())
                }
            })

我想补充一个意见。您只能调用 .string() 方法一次。如果你尝试调用它两次,它会给你非法状态异常。