Way of reopening connection in java.net.HttpURLCon

2019-08-28 22:08发布

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.

1条回答
Summer. ? 凉城
2楼-- · 2019-08-28 22:44

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:

Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances.
查看更多
登录 后发表回答