dotnetdreamer/nativescript-http-formdata

java.lang.IllegalStateException: closed

wolfchkov opened this issue · 5 comments

This error occur when read okhttp3.response.body() more then one time, because it is stream, after first read it is closing.

.....
onResponse: (call, response) => {
   let body;
   try {
       body = JSON.parse(response.body().string()); //error with parse JSON
   } catch (e) {
       body = response.body().string(); //reading body second time,  crash 
   }
.....

I found out that in my case raised error "android.os.NetworkOnMainThreadException" because of reading of response body in the httpOk callback, that executes in main thread.
I have no idea how to fix it.

Reading the response body may still block

I think this could work then.

onResponse: (call, response) => {
   let body = response.body().string();
   try {
       body = JSON.parse(body); //error with parse JSON
   } catch (e) { //ignore }
}

or a null check for body...

But, as I said earlier, the second reads of response body it is not a cause, it is a consequence of threw android.os.NetworkOnMainThreadException, because of IO operation on the main thread(The callback is made after the response headers are ready, so response body reading is a IO operation).

Seems, that one way to resolve this issue it read response body in separate thread e.g. AsyncTask.

onResponse: (call, response) => {
   let body = response.body().string(); // it is Blocking operation that execute on the main thread, 
                                                                 // so Android throws NetworkOnMainThreadException
                                                              
   try {
       body = JSON.parse(body); //error with parse JSON
   } catch (e) { //ignore }
}

@wolfchkov a temp workaround, can you try ?

var policy = new android.os.StrictMode.ThreadPolicy.Builder().permitAll().build();
android.os.StrictMode.setThreadPolicy(policy);

@wolfchkov a temp workaround, can you try ?

var policy = new android.os.StrictMode.ThreadPolicy.Builder().permitAll().build();
android.os.StrictMode.setThreadPolicy(policy);

It works for me as workaround.
Thanks