network-programming - HttpURLConnection 实现

标签 network-programming java java-6 httpurlconnection

我读到 HttpURLConnection 支持持久连接,因此一个连接可以被多个请求重用。我试过了,发送第二个 POST 的唯一方法是再次调用 openConnection。否则我得到一个 IllegalStateException("Already connected"); 我使用了以下内容:

try{
URL url = new URL("http://someconection.com");
}
catch(Exception e){}
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//set output, input etc
//send POST
//Receive response
//Read whole response
//close input stream
con.disconnect();//have also tested commenting this out
con = (HttpURLConnection) url.openConnection();
//Send new POST

第二个请求是通过同一个 TCP 连接发送的(用 wireshark 验证了它)但是我不明白为什么(尽管这是我想要的)因为我调用了 disconnect。 我检查了 HttpURLConnection 的源代码,该实现确实保留了到相同目的地的连接的保活缓存。我的问题是在发送第一个请求后,我看不到连接是如何放回缓存中的。断开连接会关闭连接,如果没有断开连接,我仍然看不到连接是如何放回缓存中的。我看到缓存有一个运行方法来遍历所有空闲连接(我不确定它是如何调用的),但我找不到连接是如何放回缓存中的。似乎唯一发生的地方是在 httpClient 的完成方法中,但这不是为带有响应的 POST 调用的。 谁能帮我解决这个问题?

编辑 我的兴趣是,什么是正确处理 HttpUrlConnection 对象以重用 tcp 连接。应该关闭输入/输出流,然后关闭 url.openConnection();每次发送新请求(避免断开连接())?如果是,当我第二次调用 url.openConnection() 时,我看不到连接是如何被重用的,因为连接已从第一次请求的缓存中删除,并且无法找到它是如何返回的。 连接是否有可能没有返回到 keepalive 缓存(错误?),但操作系统尚未释放 tcp 连接,并且在新连接上,操作系统返回缓冲连接(尚未释放)或类似的东西? 编辑2 我发现的唯一相关信息来自 JDK_KeepAlive

...when the application calls close() on the InputStream returned by URLConnection.getInputStream(), the JDK's HTTP protocol handler will try to clean up the connection and if successful, put the connection into a connection cache for reuse by future HTTP requests.

但我不确定这是哪个处理程序。 sun.net.www.protocol.http.Handler 没有像我看到的那样做任何缓存 谢谢!

最佳答案

Should input/output stream be closed followed by a url.openConnection(); each time to send the new request (avoiding disconnect())?

是的。

If yes, I can not see how the connection is being reused when I call url.openConnection() for the second time, since the connection has been removed from the cache for the first request and can not find how it is returned back.

您混淆了 HttpURLConnection 与底层 Socket它的 底层 TCP 连接。他们不一样。 HttpURLConnection 实例被 GC 处理,底层 Socket 被池化,除非您调用 disconnect()。

关于network-programming - HttpURLConnection 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3460990/

相关文章:

c++ - 网络数据包有效载荷数据是否应该在适当的边界上对齐?

ios - 将可达性与 ReactiveCocoa 集成?

network-programming - 使用 UDPConn 请求/响应对话

java - Facelets 中的 Spring Security 注销链接

java - 在正则表达式中使用命名组会导致 "Lookbehind doesn' t 有明显的最大长度“错误

c - 为什么accept()创建一个新的套接字?

java - 如何重启 kubernetes 服务的多个 spring boot 应用程序实例

java - 在 Java 的 SoapUI 5.0.0 中正确地将断言添加到 WsdlTestRequestStep

java 7套接字监听异常

java - 使代码与 java 1.6 兼容(-source 1.6 不支持 try-with-resources)