Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java
Expertise: Beginner
Jul 27, 1998



Application Security Testing: An Integral Part of DevOps

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

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?

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 ");

    try {
      url = new URL(args[0]);
    } catch(MalformedURLException e) {

    try {
      connection = url.openConnection();
      // This tells the connection to use the POST method
      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());

      // 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);
    } catch(IOException e) {
DevX Pro
Comment and Contribute






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



Thanks for your registration, follow us on our social networks to keep up-to-date