Java Reference
In-Depth Information
Notice that we needed to send our query parameters in the body of a request, and to
encode them before sending. We also had to disable following of HTTP redirects,
and to treat any redirection from the server manually. This is due to a limitation of
the HttpURLConnection class, which does not deal well with redirection of POST
requests.
In most cases, when implementing these types of more advanced HTTP applica‐
tions, developers would usually use a specialist HTTP client library, such as the one
provided by Apache, rather than coding the whole thing from scratch using JDK
classes.
Let's move on to look at the next layer down the networking stack, the Transmission
Control Protocol (TCP).
TCP
TCP is the basis of reliable network transport over the Internet. It ensures that web
pages and other Internet traffic are delivered in a complete and comprehensible
state. From a networking theory standpoint, the protocol properties that allow TCP
to function as this “reliability layer” for Internet traffic are:
Connection based
Data belongs to a single logical stream (a connection).
Guaranteed delivery
Data packets will be resent until they arrive.
Error checked
Damage caused by network transit will be detected and fixed automatically.
TCP is a two-way (or bidirectional) communication channel, and uses a special
numbering scheme (TCP Sequence numbers) for data chunks to ensure that both
sides of a communication stream stay in sync. In order to support many different
services on the same network host, TCP uses port numbers to identify services, and
ensures that traffic intended for one port does not go to a different one.
In Java, TCP is represented by the classes Socket and ServerSocket . They are used
to provide the capability to be the client and server side of the connection respec‐
tively—meaning that Java can be used both to connect to network services, and as a
language for implementing new services.
As an example, let's consider reimplementing HTTP. This is a relatively simple, text-
based protocol. We'll need to implement both sides of the connection, so let's start
with a HTTP client on top of a TCP socket. To accomplish this, we will actually
need to implement the details of the HTTP protocol, but we do have the advantage
that we have complete control over the TCP socket.
We will need to both read and write from the client socket, and we'll construct the
actual request line in accordance with the HTTP standard (which is known as RFC
2616). The resulting code will look something like this:
Search WWH ::




Custom Search