Can I call a CGI script from a servlet?

Shirish Bathe

[The following example works if the script is located behind a web server (either remote, or running on the same machine). But if you're using a standalone Java web server, and want to run (e.g.) a Perl CGI, is there any way to use System.exec() to invoke the script with the correct parameters? -Alex]

Yes, you can call CGI Script from a servlet. You can write your servlet as if it is sending data from browser. (Either using POST/ GET Method)

public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException {

    PrintWriter out = response.getWriter();
        // Put you URL/CGI here !!!
        URL url = new URL("http://localhost:8080/CgiRedir");
        URLConnection connection = url.openConnection();   
        PrintStream outStream = 
               new PrintStream(connection.getOutputStream());

        //Sending parameter to URL/CGI
          + URLEncoder.encode("Shirish")+"&datavalue="
          + URLEncoder.encode("Bathe"));


        // reading from URL
        DataInputStream inStream;
        String inputLine;

         inStream = new DataInputStream(connection.getInputStream());
         while (null != (inputLine = inStream.readLine())) {
    } catch (MalformedURLException me) {
        System.err.println("MalformedURLException: " + me);
    } catch (IOException ioe) {
        System.err.println("IOException: " + ioe);
For detail please visit :

Hope this will solve your problem.

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact