Java Reference
In-Depth Information
names a resourceyou invoke openConnection to connect to the named re-
source. 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 let-
ters and digits remain unchanged, the space character is converted to a
 
Search WWH ::




Custom Search