nativescript-http-formdata icon indicating copy to clipboard operation
nativescript-http-formdata copied to clipboard

java.lang.IllegalStateException: closed

Open wolfchkov opened this issue 5 years ago • 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 
   }
.....

wolfchkov avatar Feb 18 '20 20:02 wolfchkov

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

wolfchkov avatar Feb 18 '20 21:02 wolfchkov

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...

dotnetdreamer avatar Feb 19 '20 04:02 dotnetdreamer

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 avatar Feb 19 '20 09:02 wolfchkov

@wolfchkov a temp workaround, can you try ?

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

dotnetdreamer avatar Feb 20 '20 07:02 dotnetdreamer

@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

Fr3nky88 avatar Feb 23 '21 14:02 Fr3nky88