This works only if URL.openConnection returns java.net.HttpURLConnection; it isn't guaranteed that it will be, even if the URL is an HTTP type. To make it work reliably across all browsers (in particular, the implementation by a certain company in Washington state, at least on some versions of IE), you need to catch an exception when doing the class cast. You can still proceed, but you don't have access to setRequestMethod, which means that you must proceed with a GET request. Very annoying.
By any chance if this URL you want to contact is in the same server you can use javax.servlet.RequestDispatcher to handle the situation easily. BUt if this URL is ourside the server as our friends mentioned you need to use URLConnection class