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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With