java.net.HttpURLConnection中重新打开连接的方法

发布于 2025-01-07 20:14:28 字数 729 浏览 2 评论 0原文

首先,我打开一个连接并向服务器发送一些数据。接下来我得到回应。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼中杀气 2025-01-14 20:14:28

您需要再次调用 url.openConnection() 并获取新连接。如果请求是针对同一主机的,HttpURLConnection 应该足够智能,能够重用现有连接。引用文档:

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.

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文