First, I open a connection and send some data to server. Next I get a response.
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
wr = new OutputStreamWriter(connection.getOutputStream());
wr.write("some text sent to server");
wr.flush();
//read the server answer
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
...
What I need is to repeat the whole cycle again - send data and receive answer. The problem is that if I use the same wr object I get the IOException: stream closed. And if I try to make a new object:
wr = new OutputStreamWriter(connection.getOutputStream());
I get ProtocolException: OutputStream unavailable because request headers have already been sent!. It doesn't matter if I disconnect and make a new connection - it is all the same.
Is there any way to reopen the connection?
And I make it on Android, but I'm not really sure if it makes any difference in this situation.
You need to call
url.openConnection()
again and get a new connection.HttpURLConnection
should be smart enough to reuse the existing connection if the request is to the same host. Quote from the docs: