Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Reuse HttpUrlConnection? [duplicate]

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?

like image 559
user967710 Avatar asked Apr 27 '13 20:04

user967710


People also ask

Can I reuse HttpURLConnection?

You don't. You close this one and create a new one.

What is the difference between URLConnection and HttpURLConnection?

URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.

How do I get HttpURLConnection response code?

Set the request method in HttpURLConnection instance, default value is GET. Call setRequestProperty() method on HttpURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language” etc. We can call getResponseCode() to get the response HTTP code.

Is HttpURLConnection thread safe?

it's not thread safe. you shouldn't cache/share a connection. just create a new connection for each request. there is certainly a little overhead in creating new connections, but it is very small, you shouldn't worry about it.


1 Answers

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

like image 67
user207421 Avatar answered Oct 09 '22 01:10

user207421