Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection: Is it necessary to call connect()?

Many examples I've seen don't explicitly call connect(). Instead they just use getInputStream() or getResponseCode().

I'm assuming all of these HttpURLConnection methods that require a connection just call connect() themselves?

Are there any cases where connect() must be explicitly called for an HttpURLConnection?

like image 390
stormin986 Avatar asked May 08 '10 02:05

stormin986


People also ask

Do I need to disconnect HttpURLConnection?

Yes you need to close the inputstream first and close httpconnection next. As per javadoc. Next two questions answer depends on purpose of your connection. Read this link for more details.

How does Httpsurlconnection work?

It overrides the getHeaderField method of URLConnection class. Returns true or false depending on whether automatic instance redirection is set or not. Retrieves the permission required to connect to a destination host and port. Used to retrieve the response status from server.

What is the use of HttpURLConnection in Java?

The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only. By the help of HttpURLConnection class, you can retrieve information of any HTTP URL such as header information, status code, response code etc.

Which method of HttpURLConnection class is used to retrieve the response status from server?

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.


1 Answers

No, there are no cases. It's implicitly executed on demand. It's even specified in the documentation. Here's an extract of the URLConnection#connect() javadoc:

Operations that depend on being connected, like getContentLength, will implicitly perform the connection, if necessary.

like image 123
BalusC Avatar answered Sep 24 '22 20:09

BalusC