Professional Documents
Culture Documents
http://www.javasoft.com
Host Name -- the name of the machine
‘hosting’ the resource
try{
URL myURL = new URL (“http://www.cc.gatech.edu”);
}
catch (MalformedURLException e){
System.err.println (“This method: “ + e.toString());
}
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();
} }