Communicating With the Host
See the example applet in action in the demo or view the source code.While the security constraints built into the Java applet framework prevent applets from accessing the file system on the client machine, they can work with files located on the web host.
This is accomplished by creating a URL
object referencing a
file on the server and opening a connection to it to create an input
stream.
Opening the connection acts like an HTTP GET request to the host. The host will respond as though you had typed the URL into a browser, sending back a stream of data which can be read by the applet.
The code below shows a simple example of how to retrieve a text file from the host server and display it on the system console.
String s; URL url; InputStream in; BufferedReader buf; try { url = new URL(getDocumentBase(), "sample.txt"); } catch (Exception e) {} try { in = url.openStream(); buf = new BufferedReader(new InputStreamReader(in)); while((s = buf.readLine()) != null) System.out.println(s); } catch (IOException e) {}
Using Server-Side Scripts
For plain text files, like those with ".txt" or ".html" extensions, the data retrieved will just be the raw text data. But you can also open connections to server-side scripts or CGI programs.
The host server will treat the file request just like any other browser request and execute the script or CGI program and respond with that program's output.
For example, if the host supported ASP and you opened a file called "sample.asp" that contained this code:
<%@ LANGUAGE="VBScript" %> <% Response.Write(Time()) %>
the applet would receive a line of text containing the host's current system time.
3:57:07 PM
Likewise, you could pass data to a CGI script in the form of a URL query string.
url = new URL(getDocumentBase(), "sample.asp?name=Thomas+Edison&phone=555+4321");
Note that the data in the query string needs to be encoded ('+' for spaces,
etc.) just as with any hard-coded URL. This can be easily done using the
URLEncoder.encode()
method.
String qstring = URLEncoder.encode("name=Thomas Edison&phone=555 4321");
This technique could be used, for example, to query or update a database on the host using CGI scripts passing data much as you would using HTML forms on a web page.
The Example Applet
The example applet demonstrates reading different types of files from the web server, including an ASP script which is passed data in a query string. It defines a simple function that accepts a file name and returns the output as an ordered list of strings.
public Vector readFromHost(String filename) { String s; URL url; InputStream in; BufferedReader buf; Vector retVal; retVal = new Vector(); try { url = new URL(getDocumentBase(), filename); } catch (Exception e) { return retVal; } // Open URL and retrieve response. try { in = url.openStream(); buf = new BufferedReader(new InputStreamReader(in)); while((s = buf.readLine()) != null) retVal.addElement(s); } catch (IOException e) {} return retVal; }
Note that a Vector
is used to store the lines of text received
from the host. This is useful since the amount of data returned by the host may
vary.
Using the Host Output
Since this technique retrieves the host data as strings, you might need to
parse it and possibly convert it to other data types, like int
or
double
for use in calculations. This is fairly easy using basic
Java constructors or methods.
For example, to use the function above to retrieve numeric data from a CGI script you might code this:
// Get the third line of output as an integer. Vector v = readFromHost("sales.asp?id=53197") int i = Integer((String) v.elementAt(2));
Of course, you should always validate the data first, especially if using server-side scripts since the output can be unpredictable. As most CGI programs generate HTML code, you often find blank lines (which browsers will ignore) but which you must contend with. Also, you never know when a script might return an error message instead of the nicely formatted output you had expected.