Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
17.3 Sending Data with GET and Processing the Results Directly
439
most CGI programs are already set up to return HTML documents. How
ever, if you are developing both the client and the server sides of the process,
it seems a bit wasteful to always send back an entire HTML document; in
some cases, it would be nice to simply return data to an applet that is already
running. The applet could then present the data in a graph or some other
custom display. This approach is sometimes known as HTTP tunneling since a
custom communication protocol is embedded within HTTP: proxies, encryp
tion, server redirection, connections through firewalls, and all.
There are two main variations to this approach. Both make use of the
URL
Connection
class to open an input stream from a URL. The difference lies in
the type of stream they use. The first option is to use a
BufferedInput
Stream
or some other low level stream that lets you read binary or ASCII
data from an arbitrary server side program. That approach is covered in the
first subsection. The second option is to use an
ObjectInputStream
to
directly read high level data structures. That approach, covered in the second
subsection, is available only when the server side program is also written in
the Java programming language.
Reading Binary or ASCII Data
An applet can read the content sent by the server by first creating a
URLCon
nection
derived from the URL of the server side program and then attach
ing a
BufferedInputStream
to it. Seven main steps are required to
implement this approach on the client, as described below. I'm omitting the
server side code since the client code described here works with arbitrary
server side programs or static Web pages.
Note that many of the stream operations throw an
IOException
, so the
following statements need to be enclosed in a
try
/
catch
block.
1. Create a
URL
object referring to applet's home host. You
can pass an absolute URL string to the
URL
constructor (e.g.,
"http://host/path"
), but since browser security restrictions
prohibit connections from applets to machines other than the
home server, it makes more sense to build a URL based upon
the hostname from which the applet was loaded.
URL currentPage = getCodeBase();
String protocol = currentPage.getProtocol();
String host = currentPage.getHost();
int port = currentPage.getPort();
String urlSuffix = "/servlet/SomeServlet";
URL dataURL = new URL(protocol, host, port, urlSuffix);
Home page for this book: www.coreservlets.com; Home page for sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved