2 Minutes To Code (β Version)

Apache Commons Http Client - 2 minute tutorial

Basic usage : How to make a POST http request

This example shows how to make an HTTP POST request to an http server.

It is mostly same as making an HTTP GET request except for the use of class org.apache.commons.httpclient.methods.PostMethod. The parameters are set using the class org.apache.commons.httpclient.NameValuePair and setting then in the request object using setRequestBody() metghod of PostMethod.
package com.techfundaes.httpBag;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

public class SimplePost
{
	public static void main(String[] args)
	{
		HttpClient httpClient = new HttpClient();
		httpClient.getHostConfiguration().setProxy("202.56.254.213", 5631);
		PostMethod postMethod = new PostMethod("http://www.techfundaes.com/test.do");
		NameValuePair[] data = new NameValuePair[2];
		data[0] = new NameValuePair("section", "sports");
		data[1] = new NameValuePair("page", "euro cup");
		postMethod.setRequestBody(data);
		try
		{
			System.out.println(postMethod.getRequestHeaders());
			httpClient.executeMethod(postMethod);
			System.out.println("responseString:"+postMethod.getResponseBodyAsString());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally 
		{
			postMethod.releaseConnection();
		}
	}
}