Read this beautiful Javaworld article explaining the URL/URLConnection classes and the hidden traps:-
http://www.javaworld.com/javaworld/jw-03-2001/jw-0323-traps.html The author says that it is con.getInputStream() which actually posts the request to the server !!
1. When we do con.getOutputStream() and write to the output stream, actually that writing is done to a local buffer- NOT to the server.
2. When we do con.getInputStream()- it is now that what is in the local buffer is posted to the server !!
The author warns of several traps for eg:-
TRAP 1:
--you do con.getInputStream()
--you do con.getOutputStream()
--you write to output stream
Result=Failure: When getInputStream is done nothing has been written to the POST buffer- so nothing is posted - and subsequent opening of output stream throws exception.
TRAP 2:
--you do con.getOutputStream()
--you write to output stream and flush
--you do NOT do con.getInputStream()
Result=Failure: The writing to the output stream merely writes to local buffer. Without getInputStream() nothing is posted to the server.
TRAP 3:
--you do con.getOutputStream()
--you do con.getInputStream() //before writing to output stream
--you write to output stream and flush
Result=Failure: At the time getInputStream is done, nothing has been written to the the local POST buffer. So nothing is posted to the server even though the server/servlet is invoked. Subsequent writing is useless.
SUCCESSFUL METHOD:
--you do con.getOutputStream()
--you write to output stream and flush
--you do con.getInputStream()
Result=Success. This is the order which we must strictly and compulsorily adhere to.