AFAIK it's useless to call connect()
. Maybe by calling this the state of the HUC changes from CREATED to CONNECTED. But in all docs I've read it is sayed that it doesn't hurt to call connect()
and it's ignored if you're already connected.
So in fact, when you call a method like getInputStream()
, getContentLength()
, getOutputStream()
, the connection will be established to the server if it is not already done.
But one thing is often used wrong IMO: in many code samples you can see that getInputStream()
is called before getResponseCode()
. I've observed that getInputStream()
throws an Exception when you call it in case of HTTP status code >= 400.
So I recommend doing it this way (pseudo-code):
if (method == POST || method == PUT)
con.setDoOutput(true)
writeBody(con)
statusCode = con.getResponseCode()
if (statusCode is successful)
readStream(con.getInputStream())
else
// if you expect some information in the body in case of error...
readStream(con.getErrorStream())
You can read the whole (more involved) code here.