Java Reference
In-Depth Information
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Running this program will result in the HTML from the URL resource identified as
url1 being printed to the command line.
How It Works
Creating URLs in Java code is fairly straightforward thanks to the java.net.URL
class, which does all of the heavy lifting. An URL is a character string that points to a
resource on the Internet. Sometimes it is useful to create URLs in Java code so that you
can read content from, or push content to, the Internet resource that the URL is point-
ing to. In the solution to this recipe, a few different URL objects are created, demon-
strating the different constructors that are available for use.
The easiest route to use for creating an URL is to pass the standard readable URL
string for a resource that is located on the Internet to the java.net.URL class to cre-
ate a new instance of the URL. In the solution, an absolute URL is passed to the con-
structor to create the url1 object.
URL url1 = new URL(" http://www.java.net " );
Another useful way to create an URL is to pass two arguments to the URL con-
structor and create a relative URL. It is useful to base relative URLs on the location of
another URL. For instance, if a particular site has a number of different pages, you
could create an URL pointing to one of the subpages relative to the URL of the main
site. Such is the case with the url2 object in the solution to this recipe.
Search WWH ::




Custom Search