本文介绍了HttpURLConnection实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have read that HttpURLConnection supports persistent connections, so that a connection can be reused for multiple requests. I tried it and the only way to send a second POST was by calling openConnection for a second time. Otherwise I got a IllegalStateException("Already connected");I used the following:

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)但我无法理解为什么(虽然这是我想要的)因为我已经调用了断开连接。
我检查了HttpURLConnection的源代码,并且实现确实保持了对相同目标的连接的keepalive缓存。我的问题是,在发送第一个请求后,我无法看到连接如何放回缓存中。断开连接关闭连接,没有断开连接,仍然无法看到连接如何放回缓存。我看到缓存有一个run方法来遍历所有空闲连接(我不确定它是如何被调用的),但是我找不到连接如何放回缓存中。似乎唯一发生的地方是httpClient的完成方法,但是没有调用具有响应的POST。
有谁可以帮我这个?

The second request is send over the same TCP connection (verified it with wireshark) but I can not understand why (although this is what I want) since I have called disconnect.I checked the source code for the HttpURLConnection and the implementation does keep a keepalive cache of connections to the same destinations. My problem is that I can not see how the connection is placed back in the cache after I have send the first request. The disconnect closes the connection and without the disconnect, still I can not see how the connection is placed back in the cache. I saw that the cache has a run method to go through over all idle connections (I am not sure how it is called), but I can not find how the connection is placed back in the cache. The only place that seems to happen is in the finished method of httpClient but this is not called for a POST with a response.Can anyone help me on this?

编辑
我的兴趣是,对HttpUrlConnection的正确处理是什么用于tcp连接重用的对象。应该关闭输入/输出流,然后是url.openConnection();每次发送新请求(避免disconnect())?如果是,我第二次调用url.openConnection()时无法看到连接是如何重用的,因为第一个请求的连接已从缓存中删除,无法找到返回的连接方式。
是否有可能连接没有返回到keepalive缓存(bug?),但操作系统尚未发布tcp连接,在新连接上,OS返回缓冲连接(尚未发布)或相似的东西?
EDIT2
我找到的唯一相关内容来自

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

But I am not sure which handler is this. sun.net.www.protocol.http.Handler does not do any caching as I sawThanks!

推荐答案

是。

您将 HttpURLConnection 与基础 Socket 混淆和底层TCP连接。他们不一样。 HttpURLConnection 实例是GC'd,底层的 Socket 是汇总的,除非你打电话给断开连接()。

You are confusing the HttpURLConnection with the underlying Socket and its underlying TCP connection. They aren't the same. The HttpURLConnection instances are GC'd, the underlying Socket is pooled, unless you call disconnect().

这篇关于HttpURLConnection实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:06
查看更多