Java HTTP 全双工
我有一个在 Jersey (GlassFish 3.1.1) 上运行的 RESTful Web 服务。这个有点不寻常——它使用 HTTP 流。客户端和服务器进行长时间运行的对话,其中不断向对方发送编码为 XML 标记的消息。这样做的主要原因是服务器可以推送到客户端。
我有一个使用 HttpURLConnection
的测试客户端。问题在于客户端的 OutputStream
或服务器的 InputStream
过早关闭。当我尝试从客户端发送一些 XML 时,抛出了一个 ProtocolException
(读取输入后无法写入输出)。
当我使用 WizTools RESTClient 进行测试时,我可以发布 XML 请求,但该工具不允许保持连接处于活动状态。但至少我知道网络服务至少在这种情况下正在运行。 (在流媒体场景中可能没问题;我的猜测是 HttpURLConnection
让我失望了。
有没有办法让 HttpURLConnection 保持活动状态并让我有机会实际向 发送一些内容>OutputStream
?最重要的是,有没有办法允许它在通过InputStream
接收到数据后继续写入OutputStream
?
更新:
看起来 HttpURLConnection
正在强制执行 HTTP 的常规用法,即客户端在完全发送请求(并关闭输出流)之前无法处理响应是否有一种替代方案可以允许请求和响应暂时重叠?我刚刚开始研究 Apache HttpClient,但我还没有发现任何表明它是可能的,所以我不确定我是否在浪费我的时间。时间。
I have a RESTful web service running on Jersey (GlassFish 3.1.1). This one's a bit unusual - it uses HTTP streaming. The client and server have a long running conversation in which they keep sending each other messages encoded as XML tags. The main reason for doing this is so the server can push to the client.
I have a test client that uses HttpURLConnection
. The problem is that the either the client's OutputStream
or server's InputStream
are being closed prematurely. When I try to send a bit of XML from the client, I get a ProtocolException
thrown (cannot write output after reading input).
When I test using WizTools RESTClient, I can post an XML request, but this tool doesn't allow for keeping the connection alive. But at least I know the web service is functioning at least in this scenario. (It's probably just fine in the streaming scenario; my guess is the HttpURLConnection
is letting me down.
Is there a way to make the HttpURLConnection stay alive and give me the chance to actually send something to the OutputStream
? And, on top of that, is there a way to allow it to keep writing to the OutputStream
even after it has received data via the InputStream
?
Update:
It looks like HttpURLConnection
is enforcing the conventional usage of HTTP, namely that a client cannot process the response until it has completely sent the request (and closed the output stream). Is there an alternative that will allow for the request and response to temporally overlap? I just started looking at Apache HttpClient, but I haven't yet found anything to indicate it's possible, so I'm not sure if I'm wasting my time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从
InputStream
读取后,您不应该写入更多数据,因为这不遵循HTTP协议的本质,即请求-响应。查看更多信息 这里。You are not supposed to write more data after reading from the
InputStream
because this does not follow the nature of HTTP Protocol which is Request-Response. Check more on this here.