How can an applet or application pass data to and read output from a CGI script or Servlet?

Tim Rohaly

To pass data to a CGI program or Servlet, you need to use the GET or POST method in HTTP. The data is sent as key=value pairs separated by ampersands. To do this in Java, we use the URLConnection class, which takes care of the details of the HTTP protocol for us. The only thing we have to specify is the URL of the server and the data to be sent.

As an example, here is an application that looks up a word in the Merriam-Webster online dictionary:

import java.net.*;
import java.io.*;

public class Post {

    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.m-w.com/cgi-bin/dictionary");
            URLConnection connection = url.openConnection();
            OutputStreamWriter ostream = new OutputStreamWriter(connection.getOutputStream());
            BufferedWriter out = new BufferedWriter(ostream);

            InputStream stream = connection.getInputStream();
            BufferedInputStream in = new BufferedInputStream(stream);
            int i = 0;
            while ((i = in.read()) != -1) {
        catch (MalformedURLException e) {
        catch (IOException ee) {
Note that the data is sent using the write() method of the URLConnection's output stream. This data must be URL-encoded (use the URLEncoder class to do this). In the example above, the data is unchanged after URL-encoding.

The same technique may be used by an applet. However, browser security restrictions usually prevent an applet from connecting to a host other than the one from which the applet class was downloaded.

Note that is works not just for CGI scripts and Servlets, but for any server-side mechanism you use to handle GET and POST requests, for instance a JSP page.