java.net.HttpURLConnection中重新打开连接的方法
首先,我打开一个连接并向服务器发送一些数据。接下来我得到回应。
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()));
...
我需要的是再次重复整个周期 - 发送数据并接收答案。问题是,如果我使用相同的 wr 对象,我会得到 IOException:流已关闭。如果我尝试创建一个新对象:
wr = new OutputStreamWriter(connection.getOutputStream());
我得到ProtocolException: OutputStream unavailable,因为请求标头已被发送!。如果我断开连接并建立新连接并不重要 - 都是一样的。
有什么办法可以重新打开连接吗?
我在 Android 上制作了它,但我不确定它在这种情况下是否有任何区别。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要再次调用 url.openConnection() 并获取新连接。如果请求是针对同一主机的,
HttpURLConnection
应该足够智能,能够重用现有连接。引用文档: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: