Networking - Using Java to login to a website with the POST method of http


HttpClient was started in 2001 as a subproject of the Jakarta Commons, based on code developed by the Jakarta Slide project. It was promoted out of the Commons in 2004, graduating to a separate Jakarta project. In 2005, the HttpComponents project at Jakarta was created, with the task of developing a successor to HttpClient 3.x and to maintain the existing codebase until the new one is ready to take over. The Commons project, cradle of HttpClient, left Jakarta in 2007 to become an independent Top Level Project. Later in the same year, the HttpComponents project also left Jakarta to become an independent Top Level Project, taking the responsibility for maintaining HttpClient with it.

Using Apache's HttpClient we can easily implement a client side application that interacts with a web application or any HTTP based web services.

Below is a sample code posted by lobhater @ forums.sun.com

There are many another examples available at Apache's HttpComponents project page also.


package hackthissiteapp1;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

public class Main
{

public static void main(String[] args) throws Exception {

HttpClient client = new HttpClient();

GetMethod getPage = new GetMethod("http://www.hackthissite.org");

client.executeMethod(getPage);

PostMethod postLogin = new PostMethod("http://www.hackthissite.org/pages/index/index2.php");

NameValuePair[] data = {
new NameValuePair("txt_username", "MYUSERNAME"),
new NameValuePair("txt_password", "MYPASSWORD"),
new NameValuePair("btn_submit","Login")

};

postLogin.setRequestBody(data);

client.executeMethod(postLogin);


//this is a request to a page that requires authentication 
GetMethod getPage2 = new GetMethod("http://www.hackthissite.org/missions/basic/");

client.executeMethod(getPage2);

System.out.println(getPage2.getResponseBodyAsString());

 }
}

Popular posts from this blog

Java XML getElementById returning null, fix using XPath

Sending an Email to Multiple Recipients - Cc: and Bcc:

Store your 450GB data on an A4 size paper: THE RAINBOW TECHNOLOGY