Java 如何重用HttpUrlConnection?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16256681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:02:01  来源:igfitidea点击:

How to Reuse HttpUrlConnection?

javahttpservletshttpurlconnection

提问by user967710

I am interested in reusing an HttpUrlConnection (as part of a statefull protocol between server and client that I'm developing). I know that there is an Connection=keep-alive header for persistent http. Now, I want to know how to reuse such a conenction. I have written this code:

我对重用 HttpUrlConnection(作为我正在开发的服务器和客户端之间的有状态协议的一部分)感兴趣。我知道有一个 Connection=keep-alive 标头用于持久的 http。现在,我想知道如何重用这样的连接。我写了这段代码:

URL u = new java.net.URL("http://localhost:8080/Abc/Def");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Connection", "keep-alive");
c.setHeader("A","B");
c.getInputStream() //here I see that server gets my messages (using DEBUG)
c.setHeader("B","C"); //

Now how do I resend this "B" header to the server, I tried re-connect etc,but nothing gets it to work.

现在如何将这个“B”标头重新发送到服务器,我尝试重新连接等,但没有任何效果。

And the server also perform response.setHeader("Connection", "keep-alive");

而且服务器也执行 response.setHeader("Connection", "keep-alive");

I've looked in many forums, but no one wrote about this. Maybe HttpURLConnectiondoesn't handle this?

我看了很多论坛,但没有人写过这个。也许HttpURLConnection不处理这个?

采纳答案by user207421

You don't. You close this one and create a new one. It does TCP connection pooling and keepalive behind the scenes.

你没有。你关闭这个并创建一个新的。它在幕后进行 TCP 连接池和 keepalive。