If I create an HTTP java.net.URL and then call openConnection() on it, does it necessarily imply that an HTTP post is going to happen? I know that openStream() implies a GET. If so, how do you perform one of the other HTTP verbs without having to work with the raw socket layer?
If I create an HTTP java.net.URL and then call openConnection() on it, does it
Share
If you retrieve the
URLConnectionobject usingopenConnection()it doesn’t actually start communicating with the server. That doesn’t happen until you get the stream from theURLConnection(). When you first get the connection you can add/change headers and other connection properties before actually opening it.URLConnection’s life cycle is a bit odd. It doesn’t send the headers to the server until you’ve gotten one of the streams. If you just get the input stream then I believe it does a GET, sends the headers, then lets you read the output. If you get the output stream then I believe it sends it as a POST, as it assumes you’ll be writing data to it (You may need to call
setDoOutput(true)for the output stream to work). As soon as you get the input stream the output stream is closed and it waits for the response from the server.For example, this should do a POST:
While this would do a GET:
URLConnectionwill also do other weird things. If the server specifies a content length thenURLConnectionwill keep the underlying input stream open until it receives that much data, even if you explicitly close it. This caused a lot of problems for us as it made shutting our client down cleanly a bit hard, as theURLConnectionwould keep the network connection open. This probably probably exists even if you just usegetStream()though.