URL
Objectsjava.net.URL
class. All can throw MalformedURLExceptions.
public URL(String u) throws MalformedURLException
public URL(String protocol, String host, String file)
throws MalformedURLException
public URL(String protocol, String host, int port, String file)
throws MalformedURLException
public URL(URL context, String u) throws MalformedURLException
Given a complete absolute URL like http://www.poly.edu/schedule/fall97/bgrad.html#cs,
you construct a URL
object for that URL like this:
URL u = null;
try {
u = new URL("http://www.poly.edu/schedule/fall97/bgrad.html#cs");
}
catch (MalformedURLException e) {
}
You can also construct the URL by passing its pieces to the constructor,
like this:
URL u = null;
try {
u = new URL("http", "www.poly.edu", "/schedule/fall97/bgrad.html#cs");
}
catch (MalformedURLException e) {
}
You don't normally need to specify a port for a URL. Most protocols have default ports.
For instance, the http port is 80; but sometimes this does change and in that case you can use
the third constructor:
URL u = null;
try {
u = new URL("http", "www.poly.edu", 80, "/schedule/fall97/bgrad.html#cs");
}
catch (MalformedURLException e) {
}
Finally, many HTML files contain relative URLs. For example, this page's URL is
http://metalab.unc.edu/javafaq/course/week12/07.html. However, this entire site is mirrored
in several places around the world. Rather than having to rewrite the internal links
for each mirror site, relative URLs inherit the host, port, protocol, and possibly
directory from the current page. Thus on this page a link to "08.html" refers to
http://metalab.unc.edu/javafaq/course/week12/08.html. However when this same page is loaded
from http://sunsite.lanet.lv/javafaq/course/week12/07.html, then the link to "08.html"
refers to http://sunsite.lanet.lv/javafaq/course/week12/08.html instead.The fourth constructor above creates URLs relative to a given URL. For example,
URL u1, u2;
try {
u1 = new URL("http://metalab.unc.edu/javafaq/course/week12/07.html");
u2 = new URL(u1, "08.html");
}
catch (MalformedURLException e) {
}
This is particularly useful when parsing HTML.