问题
I am doing two succssive calls to my servlet from android in 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've closed the outputstream of the first connection after closing the inputstream. But If I close the outputstream after sending the object, the second input stream throws an exception:
java.io.StreamCorruptedException
Why should the outputstream be closed after closing the inputstream?
NOTE
If someone knows the actual answer or the proper reason as to why it does not work in Android, please answer. Till then I will accept the answer given by EJP - that it is a bug in android.
回答1:
Looks like a bug in Android to me.
In Java whence this comes, closing the ObjectOutputStream
at any time over an HttpURLConnection
does nothing except flush the output (because the connection has to stay up to receive the response). Closing the input stream of an HttpURLConnection
closes the entire connection, so a subsequent close of the ObjectOutputStream
would do nothing.
I suspect Android does something bad to the connection when you do the ObjectOutputStream.close()
first, such as closing it.
I would omit the ObjectOutputStream.close()
altogether, you don't need it in either platform. The flush()
is sufficient.
来源:https://stackoverflow.com/questions/9701872/why-should-outputstream-be-closed-after-inputstream-in-android