Thursday, February 14, 2008

How to send a POST Request with Parameters From a Java Class

his example shows how to sent a POST request to a server with attached parameters. Two parameters are sent in the example code below, width and height. We use the URL and URLConnection classes to open the connection to the destination. Then the output stream is retrieved by calling getOutputStream() on the URLConnection object. With the output stream we can write the parameters and then start reading the response from the server using the input stream which we get by calling getInputStream() on the same URLConnection object. We assume there will only be character based content returned from the server so we use the BufferedWriter to read the response line by line.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
 * Main.java
 *
 * @author www.javadb.com
 */
public class Main {
    
    /**
     * Extends the size of an array.
     */
    public void sendPostRequest() {
        
        //Build parameter string
        String data = "width=50&height=100";
        try {
            
            // Send the request
            URL url = new URL("http://www.somesite.com");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            
            //write parameters
            writer.write(data);
            writer.flush();
            
            // Get the response
            StringBuffer answer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                answer.append(line);
            }
            writer.close();
            reader.close();
            
            //Output the response
            System.out.println(answer.toString());
            
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().sendPostRequest();
    }
}
 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory