THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

A URL object stores a URL, providing methods to examine and set its various parts (protocol, host, port
number, and file). A URL object simply names a resourceyou invoke openConnection to connect to the
named resource. The openConnection method returns a URLConnection object that lets you get the
header fields and content of the resource as input and output streams. The following program reads the
contents of a URL:


import java.net.;
import java.io.
;


public class ReadURL {
public static void main(String[] args) {
for (String url : args) {
try {
readURL(url);
} catch (Exception e) {
System.err.println(url + ":");
e.printStackTrace();
}
}
}


private static void readURL(String name)
throws MalformedURLException, IOException
{
URL url = new URL(name);
URLConnection connect = url.openConnection();
InputStream in = connect.getInputStream();
byte[] bytes = new byte[1024];


int len; // number of bytes actually read
while ((len = in.read(bytes)) >= 0)
System.out.write(bytes, 0, len);
}
}


The URLEncoder class lets you turn an ISO Latin-1 string (such as a user-typed query) into a form that can
be included as part of a URL. ASCII letters and digits remain unchanged, the space character is converted to a
+, and all other characters are represented by their lower 8 bits in hex preceded by a %.


The File.toURL method creates a file URL for the path specified by that File object.


You can create DatagramSocket objects for sockets that send and receive DatagramPacket objects,
which contain an array of bytes. Datagrams are a connectionless packet delivery service, in which packets are
individually addressed and routed and could be received in any order. With the MulticastSocket
subclass of DatagramSocket, you can set up a socket that can send and receive packets to and from
multiple addresses.


25.6. java.rmi Remote Method Invocation


When you can download and run code on other systems, the face of distributed computing changes. The Java
platform's Remote Method Invocation (RMI) gives you a way to create objects whose methods can be invoked
from other virtual machines, including those running on completely different hosts. Because RMI is designed
for communicating between Java virtual machines it can take advantage of the architecture's features and can
operate in a natural fashion for programmers. RMI is contained in the package java.rmi and its
subpackages, most notably the package java.rmi.server for RMI server implementations.

Free download pdf