devxlogo

Talk to a cgi-bin on WEB in POST method not GET

Talk to a cgi-bin on WEB in POST method not GET

Question:
I know how to fetch content of a URL address in Java, but what do I to write to a CGI script using the HTTP POST method?

Answer:
Passing arguments or data to a CGI script via the POST method is not immediately obvious to the Java programmer attempting to do this for the first time. By default, the URLConnection class uses the GET method, in which case you pass your arguments as part of the URL. To use the POST method, you have to call setDoOutput with an argument of true, get the connection’s output stream, and write your POST data to the stream. After you close the stream, you can start reading from connection’s input stream to obtain the output of the CGI script. The code listing shows how to do this. It takes a URL of a CGI script as an argument, connects to the URL, and reads the POST data from standard input until it encounters the end of file (you can use Ctrl-D). After you’re done typing in the POST data, the example program fetches the output from the CGI script and prints it to standard output.

import java.io.*;import java.net.*;public final class Post {  public static final void main(String args[]) {    String input;    URL url;    URLConnection connection;    InputStream result;    BufferedReader reader;    BufferedWriter writer;    byte[] buffer = new byte[1024];    int bytes;    if(args.length != 1) {      System.err.println("usage: Post ");      return;    }    try {      url = new URL(args[0]);    } catch(MalformedURLException e) {      e.printStackTrace();      return;    }    try {      connection = url.openConnection();      // This tells the connection to use the POST method      connection.setDoOutput(true);      writer =	new BufferedWriter(		   new OutputStreamWriter(connection.getOutputStream()));      // Read the POST data from standard input until EOF      reader = new BufferedReader(new InputStreamReader(System.in));      while((input = reader.readLine()) != null) {	writer.write(input, 0, input.length());	writer.write("
");      }      writer.flush();      writer.close();      // Now that we've written the POST data, we can fetch the contents      // of the URL.      result = connection.getInputStream();      while((bytes = result.read(buffer)) > -1)	System.out.write(buffer, 0, bytes);      System.out.flush();    } catch(IOException e) {      e.printStackTrace();      return;    }  }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist