You are on page 1of 6

URLs

A URL specifies the location of networked resource--a file, for example.


A common URL is one for a web resource:

http://www.javasoft.com
Host Name -- the name of the machine
‘hosting’ the resource

Other protocols are possible: Filename -- the pathname to the file on


the host
ftp://
Port Number -- the port number to
file:// which to connect (optional).

jdbc:// Reference -- a reference to a named


anchor within a resource that usually
identifies a specific location within a
file (optional).
URLs
The easiest way to create a URL in Java is to start with a String:

try{
URL myURL = new URL (“http://www.cc.gatech.edu”);
}
catch (MalformedURLException e){
System.err.println (“This method: “ + e.toString());
}

URLs can also be created relative to an existing URL:

try{
URL firstURL = new URL(“http://www.foo.com/top_level”);
URL secondURL =
new URL (firstURL, “lower_level”);
}
catch (Exception e){;}
Using URLs
URLs contain many useful methods, including:

getProtocol();
returns the protocol identifier component of the URL (ftp/http,
e.g.).

getHost();
returns the host name component of the URL.

getPort();
returns the port number component of the URL (or -1 if not set).

getFile();
returns the filename component of the URL.

getRef();
returns the reference component of the URL.
import java.net.*;
import java.io.*;
public class URLReaderExample {
public static void main
(String[] args) throws Exception {
if (args.length == 0) showUsage();
URL myURL = new URL("http://” + args[0]);
BufferedReader in =
new BufferedReader(new InputStreamReader
(myURL.openStream()));
String strInput;
while ((strInput = in.readLine()) != null)
System.out.println(strInput);
in.close();
}
public static void showUsage(){
System.err.println
("Usage:\n\tjava URLReaderExample <IP Address>");
System.exit(0);
}//showUsage
}//URLReaderExample
Connecting to a URL
One can also use “openConnection()” to connect to a URL. This
creates a communication link between your Java program and the
URL over the network. For example:
try {
URL myURL =
new URL("http://www.blarg.foo.org/");
myURL.openConnection();
}
catch (MalformedURLException e)
{
;
}
catch (IOException e)
{
;
}
One can then interact with the remote URL. (E.g., POST information
to web pages
Extracting the Stream from a URL
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main
(String[] args) throws Exception {
URL myURL =
new URL("http://www.cc.gatech.edu/");
URLConnection uc = myURL .openConnection();
BufferedReader in = new BufferedReader
(new InputStreamReader
(uc.getInputStream()));
/* see also getOutputStream() */
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} }

You might also like