从休息服务,我收到以下JSON respoonse
{"code":1,"message":"success","status":"success","users":[{"email":"qqq@aa.aa","name":"qq"},{"email":"dd@dd.dd","name":"dd"},{"email":"cc@vv.vv","name":"cc"},{"email":"qq@qq.qq","name":"qq"},{"email":"qq@qq.qq","name":"qq"}]}
当我尝试将其转换为JSONObject时,会引发错误,
这就是我尝试提取JSON响应的方式,
jsonObject = new JSONObject(response.body().string());
从上面的脚本引发了错误。错误如下
E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example.ej.ziphiotest, PID: 21945
java.lang.IllegalStateException: closed
at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:408)
at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:402)
at okhttp3.internal.Util.bomAwareCharset(Util.java:432)
at okhttp3.ResponseBody.string(ResponseBody.java:174)
at com.example.ej.ziphiotest.requests.UserRequest$1.onResponse(UserRequest.java:85)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
编辑:
这是要求:
final Request request = new Request.Builder()
.header("key", params[0])
.url(URL)
.build();
try {
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.code() == 200){
try {
jsonObject = new JSONObject(response.body().string());
restResponse = new RestResponse(jsonObject.getString("status"), jsonObject.getString("code"), jsonObject.getString("message"), null, jsonObject.getJSONArray("users"));
onTaskComplete.onTaskComplete(restResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
我想念的地方。谢谢您的宝贵时间
最佳答案
问题是我在很短的时间内两次使用了response.body().string()
。 AS @Firoz Memon在评论中说。
尝试将其存储在变量中,然后使用变量而不是response.body()。string()代码。由于响应主体可能很大,因此OkHttp不会将其存储在内存中,因此它会在需要时将其作为网络流读取。当您将主体读为字符串()时,OkHttp会下载响应主体并将其返回给您,而无需保留对该字符串的引用,因此,如果没有新的请求,就无法将其下载两次。
从@Firoz Memon复制过来,并从上方注释。
原始参考:https://github.com/square/okhttp/issues/1240
关于java - 从JSON响应中提取值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53293364/