Talk to a CGI/ServletTag(s): Networking Servlet/JSP

From the client point of view, there is no difference talking to CGI or Servlet. There is two ways to send a request to a CGI. The GET method contains encoded parameters in the URL. A typical URL talking to CGI using the GET method would be:
new URL("");
Here we calling a script called (a PERL script) passing the parameters name and site. Parameters are encoded, spaces are changed to "+" and special character to hexadecimal using a 3-letter escape sequence. Each parameter is delimited by the character "&". Habitually the encoding is done through the static method encode of the class.
String theCGI = "";
String encoded = "name=" + URLencoder.encode("Real Gagnon");
URL cgiurl = new URL(thecgi + encoded);
Once the URL is constructed, you call the CGI using the showDocument method (Applet).
The CGI will process the result and produce a page to be displayed.

The POST method allows the programmer to manipulate the data received from the CGI. First a connection is made to the CGI, an OutputStream is open to send the parameters (if any). Then InputStream is created to receive the result.

String theCGI = "";
String encoded = "name=" + URLencoder.encode("Real Gagnon");
URL CGIurl = new URL(theCGI);

URLConnection c = CGIurl.openConnection();
DataOutputStream out = new DataOutputStream(c.getOutputStream());
out.flush(); out.close();

BufferedReader in =
   new BufferedReader(new InputStreamReader(c.getInputStream());

String aLine;
while ((aLine = in.readLine()) != null) {
   // data from the CGI
You can't do some output then some input and do again some output. You must do all the output and then the input. There is no "dialog" between the client and the server. The client make a request and the server send back the result and close the connection.
blog comments powered by Disqus