OkHttp如何获取Json字符串?

新手上路,请多包涵

解决方案:这是我这边的错误。

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

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

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

有人可以帮忙吗?

原文由 Haifeng Zhang 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 501
2 个回答
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);

原文由 Newbies 发布,翻译遵循 CC BY-SA 3.0 许可协议

我也面临同样的问题

使用此代码:

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

它绝对有效

原文由 Venkat Veeravalli 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题