Java Reference
In-Depth Information
The
URL
class provides several methods for obtaining URL information. The
following application (based on a program in Sun's Java Tutorial on networking)
breaks apart and displays the components of a complete URL string:
import java.net.*;
import java.io.*;
/** Parse a URL address into its components. **/
public class
ParseAddress
{
public static void main (String[] args) {
if (args.length!=1) {
System.out.println (
"Error: missing url parameter");
System.out.println (
"Usage: java ParseAddress <url>");
System.exit (0);
}
try {
URL url = new URL (args[0]);
System.out.println ("Protocol ="+
url.getProtocol ());
System.out.println (
"
Host
="
+ url.getHost ());
System.out.println (
"
Port
="
+ url.getPort ());
System.out.println (
"
File name
="
+
url.getFile ());
System.out.println (
"
Target
="
+ url.getRef ());
}
catch (MalformedURLException e)
{
System.out.println (
"
Bad URL
="
+ arg[0]);
}
}
} // class ParseAddress
Running the program with a URL string on the command line produces the
following:
c:
\
>java ParseAddress
http://www.myschool.edu:80/data/x.html#d
Protocol
=
http
Host
=
www.myschool.edu
Search WWH ::
Custom Search