Way of reopening connection in java.net.HttpURLConnection

末鹿安然 提交于 2019-12-12 03:17:17

问题


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:


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.


来源:https://stackoverflow.com/questions/9370378/way-of-reopening-connection-in-java-net-httpurlconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!