Java Reference
In-Depth Information
Networking in Java
Networking is the capability of different computers to make connections with each other
and to exchange information. In Java, basic networking is supported by classes in the
java.net package, including support for connecting and retrieving files by Hypertext
Transfer Protocol (HTTP) and File Transfer Protocol (FTP), as well as working at a
lower level with sockets.
You can communicate with systems on the Net in three simple ways:
Load a web page and any other resource with a uniform resource locator (URL)
from an applet.
n
Use the socket classes, Socket and ServerSocket , which open standard socket
connections to hosts and read to and write from those connections.
n
Call getInputStream() , a method that opens a connection to a URL and can
extract data from that connection.
n
Opening a Stream over the Net
As you learned during Day 15, “Working with Input and Output,” you can pull informa-
tion through a stream into your Java programs in several ways. The classes and methods
you choose depend on the format of the information and what you want to do with it.
One of the resources you can reach from your Java programs is a text document on the
web, whether it's a Hypertext Markup Language (HTML) file, Extensible Markup
Language (XML) file, or some other kind of plain text document.
You can use a four-step process to load a text document off the Web and read it line
by line:
1. Create a URL object that represents the resource's web address.
2. Create a HttpURLConnection object that can load the URL and make a connection
to the site hosting it.
3. Use the getContent() method of that HttpURLConnection object to create an
InputStreamReader that can read a stream of data from the URL.
4. Use that input stream reader to create a BufferedReader object that can efficiently
read characters from an input stream.
There's a lot of interaction going on between the web document and your Java program.
The URL is used to set up a URL connection, which is used to set up an input stream
reader, which is used to set up a buffered input stream reader. The need to catch any
exceptions that occur along the way adds more complexity to the process.
 
Search WWH ::




Custom Search