使用 OkHttp 返回信息时,将 response.body().string() 转成对象,结果直接闪退
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "onResponse: " + response.body().string());
try{
JSONArray jsonArray=new JSONArray(response.body().string());
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
Integer id=jsonObject.getInt("id");
String projectName=jsonObject.getString("projectName");
String managementUnit=jsonObject.getString("managementUnit");
String address=jsonObject.getString("address");
String startTime=jsonObject.getString("startTime");
String endTime=jsonObject.getString("endTime");
projectList.add(new Project(id,projectName,managementUnit,address,startTime,endTime));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
报错如下:
09-05 14:42:17.606: E/AndroidRuntime(28219): Caused by: java.lang.IllegalStateException: closed
09-05 14:42:17.606: E/AndroidRuntime(28219): at okhttp3.internal.http.Http1xStream$ChunkedSource.read(Http1xStream.java:414)
09-05 14:42:17.606: E/AndroidRuntime(28219): at okio.Buffer.writeAll(Buffer.java:993)
09-05 14:42:17.606: E/AndroidRuntime(28219): at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:106)
09-05 14:42:17.606: E/AndroidRuntime(28219): at okhttp3.ResponseBody.bytes(ResponseBody.java:128)
09-05 14:42:17.606: E/AndroidRuntime(28219): at okhttp3.ResponseBody.string(ResponseBody.java:154)
09-05 14:42:17.606: E/AndroidRuntime(28219): at com.example.nettest.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:78)
09-05 14:42:17.606: E/AndroidRuntime(28219): at com.example.nettest.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:1)
09-05 14:42:17.606: E/AndroidRuntime(28219): at android.os.AsyncTask$2.call(AsyncTask.java:292)
09-05 14:42:17.606: E/AndroidRuntime(28219): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-05 14:42:17.606: E/AndroidRuntime(28219): ... 4 more
这个错误是由于==body().string()==调用了多次导致的,==string()==仅可调用一次。
|