How to Reuse HttpUrlConnection? [duplicate]

故事扮演 提交于 2019-11-26 11:28:39

问题


This question already has an answer here:

  • Persistent HttpURLConnection in Java 2 answers

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:

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.

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

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


回答1:


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



来源:https://stackoverflow.com/questions/16256681/how-to-reuse-httpurlconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!