CGI Communications
CGI programs running in conjuction with a Web server may be connected to by a Java program. This capability is especially suited to applets which need to simulate standard HTML form functionality, which typically invokes server side programs through the action attribute of the <FORM> tag.
Two main methods of communication exist when passing information to CGI scripts, the GET operation and the POST operation.
GET method
The GET method sends name-value pairs to the CGI program appended to the URL address itself. A typical URL request has the following form:
http://www.website.com/cgi-bin/program.cgi?name=Smith&address=Oak
GET is used as the default method for all web requests. When a user makes a simple request for a web page, the browser issues the request as a "GET /" request. One problem with using GET is that the amount of data that can be passed is limited since it has to be appended to the request URL.
Here's an example of using a GET request:
String urlAddress = "http://www.website.com/cgi-bin/";
String getString = "program.cgi?name=Smith&address=Oak";
try{
URL url = newURL(urlAddress+getString);
URLConnection c = url.openConnection();
InputStream in =
c.getInputStream();
...
}
catch (Exception e) {
System.out.println("Error: " + e);
}
POST method
The POST method encodes the data in name-value pairs as well, but sends the data after all the request headers have been sent to the server. It includes the request header content-length so that the CGI program can figure out how much data to read. There's no limitation on how much data can be sent to the server program using POST. A request to the server using POST would look something like this:
POST /cgi-bin/program.cgi HTTP/1.0 ....header information... Content-length:22 name=Smith&address=Oak
Here's an example of using a POST request:
String urlAddress = "http://www.website.com/cgi-bin/program.cgi";
try{
URL url = new URL(urlAddress);
URLConnection c = url.openConnection();
c.setDoOutput(true);
OutputStream out = c.getOutputStream();
BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(out));
buf.write("name=Smith&address=Oak");
buf.write("\n");
buf.close();
}
catch (Exception e) {
System.out.println("Error: " + e);
}
Output streaming is disabled by default in the URLConnection class. To setup the URLConnection object for posting, execute the setDoOutput() methods with a parameter of true.
Next... page 11-6