Why should OutputStream be closed after entering android

I make two succssive calls to my servlet from android this way:

//FIRST CONNECTION URL url = new URL("http://172.16.32.160:8080/xyz/check_availability"); HttpURLConnection connection =(HttpURLConnection) url.openConnection(); connection.setDoOutput(true); ObjectOutputStream out=new ObjectOutputStream(connection.getOutputStream()); String a="xya"; String b="xsw"; out.writeObject(a); out.flush(); ObjectInputStream in=new ObjectInputStream(connection.getInputStream()); String s=(String) in.readObject(); in.close(); out.close(); Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_LONG).show(); //SECOND CONNECTION URL url1 = new URL("http://172.16.32.160:8080/xyz/check_availability"); HttpURLConnection connection1 = (HttpURLConnection)url1.openConnection(); connection1.setDoOutput(true); ObjectOutputStream out1=new ObjectOutputStream(connection1.getOutputStream()); out1.writeObject(b); out1.flush(); ObjectInputStream in1=new ObjectInputStream(connection1.getInputStream()); String str=(String) in1.readObject(); in1.close(); out1.close(); Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_LONG).show(); 

The above code works well because I closed the output stream of the first connection after closing the input stream. But if I close the output stream after sending the object, the second input stream throws an exception:

 java.io.StreamCorruptedException 

Why should the output stream be closed after the input stream is closed?

Note
If someone knows the actual answer or the correct reason why it is not working on Android, please respond. Until then, I agree with the answer given by EJP - that this is a bug in android.

+4
source share
1 answer

Looks like a bug in Android for me.

In Java, where this comes from, closing the ObjectOutputStream at any time via the HttpURLConnection does nothing but reset the output (because the connection must remain valid in order to get an answer). Closing the HttpURLConnection input stream closes the entire connection, so subsequent closure of the ObjectOutputStream do nothing.

I suspect Android is doing something bad for the connection when you first do ObjectOutputStream.close() , for example, close it.

I would generally omit ObjectOutputStream.close() , you do not need it on any of the platforms. flush() enough.

+3
source

Source: https://habr.com/ru/post/1401365/


All Articles