|
|
Working with URLs |
After you've successfully created aURLobject, you can call theURLobject'sopenConnectionmethod to connect to it. When you connect to aURL, 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 site with the following code:If possible, thetry { URL yahoo = new URL("http://www.yahoo.com/"); yahoo.openConnection(); } catch (MalformedURLException e) { // new URL() failed . . . } catch (IOException e) { // openConnection() failed . . . }openConnectionmethod creates a newURLConnection(if an appropriate one does not already exist), initializes it, connects to the URL, and returns theURLConnectionobject. If something goes wrong--for example, the Yahoo server is down--then theopenConnectionmethod throws an IOException.Now that you've successfully connected to your URL, you can use the
URLConnectionobject to perform actions such as reading from or writing to the connection. The next section shows you how.
|
|
Working with URLs |