Working with URLs |
After you've successfully created a URL, you can call the URL'sopenConnection()
method to connect to it. When you connect to a URL you are initializing a communication link between your Java program and the URL over the network. For example, you can open a connection to the Yahoo search engine site with the following code:If possible, thetry { URL yahoo = new URL("http://www.yahoo.com/"); yahoo.openConnection(); } catch (MalformedURLException e) { // generated from new URL() . . . } catch (IOException e) { // generated from openConnection() . . . }openConnection()
method creates a new URLConnection (if an appropriate one does not already exist), initializes it, connects to the URL and returns the URLConnection object. If something goes wrong, like the yahoo server is down, then theopenConnection()
method throws an IOException.Now that you've successfully connected to your URL you can use the URLConnection object to read from or write to the connection among other things. The next section of this lesson shows you how to read from and write to a URLconnection.
See also
java.net.URLConnection
Working with URLs |