Java Reference
In-Depth Information
CHAPTER 5
Networking
Sun Microsystems has long used the slogan “The Network is the Computer.” It's no
surprise, therefore, that they designed Java to be a network-centeric language. The
java.net
package provides powerful and easy-to-use networking capabilities. The
examples in this chapter demonstrate those capabilities at a number of different
levels of abstraction. They show you how to:
•
Use the
URL
class to parse URLs and download the network resources speci-
fied by a URL
•
Use the
URLConnection
class to gain more control over the downloading of
network resources
•
Write client programs that use the
Socket
class to communicate over the net-
work
•
Use the
Socket
and
ServerSocket
classes to write servers
•
Send and receive low-overhead datagram packets
Downloading the Contents of a URL
Example 5-1 shows how you can download the network resource referred to by a
URL using the
URL
class. This class serves mainly to represent and parse URLs but
also has several important methods for downloading URLs. The most high-level of
these methods is
getContent()
, which downloads the content of a URL, parses it,
and returns the parsed object. This method relies on special content handlers hav-
ing been installed to perform the parsing. By default, the Java SDK has content
handlers for plain text and for several common image formats. When you call the
getContent()
method of a
URL
object that refers to a plain text or GIF or JPEG
image file, the method returns a
String
or
Image
object. More commonly, when
getContent()
doesn't know how to handle the data type, it simply returns an
InputStream
so that you can read and parse the data yourself.