Apache HttpClient - Form-Based Login


Advertisements

Using the HttpClient library you can send a request or, login to a form by passing parameters.

Follow the steps given below to login to a form.

Step 1 - Create an HttpClient object

The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object −

CloseableHttpClient httpClient = HttpClients.createDefault();

Step 2 - Create a RequestBuilder object

The class RequestBuilder is used to build request by adding parameters to it. If the request type is PUT or POST, it adds the parameters to the request as URL encoded entity

Create a RequestBuilder object (of type POST) using the post() method.

//Building the post request object
RequestBuilder reqbuilder = RequestBuilder.post();

Step 3 - Set Uri and parameters to the RequestBuilder.

Set the URI and parameters to the RequestBuilder object using the setUri() and addParameter() methods of the RequestBuilder class.

//Set URI and parameters
RequestBuilder reqbuilder = reqbuilder.setUri("http://httpbin.org/post");
reqbuilder = reqbuilder1.addParameter("Name", "username").addParameter("password", "password");

Step 4 - Build the HttpUriRequest object

After setting the required parameters, build the HttpUriRequest object using the build() method.

//Building the HttpUriRequest object
HttpUriRequest httppost = reqbuilder2.build();

Step 5 - Execute the request

The execute method of the CloseableHttpClient object accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object.

Execute the HttpUriRequest created in the previous steps by passing it to the execute() method.

//Execute the request
HttpResponse httpresponse = httpclient.execute(httppost);

Example

Following example demonstrates how to logon to a form by sending login credentials. Here, we have sent two parameters − username and password to a form and tried to print the message entity and status of the request.

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;

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

      //Creating CloseableHttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();
 
      //Creating the RequestBuilder object
      RequestBuilder reqbuilder = RequestBuilder.post();

      //Setting URI and parameters
      RequestBuilder reqbuilder1 = reqbuilder.setUri("http://httpbin.org/post");
      RequestBuilder reqbuilder2 = reqbuilder1.addParameter("Name", 
         "username").addParameter("password", "password");

      //Building the HttpUriRequest object
      HttpUriRequest httppost = reqbuilder2.build();

      //Executing the request
      HttpResponse httpresponse = httpclient.execute(httppost);

      //Printing the status and the contents of the response
      System.out.println(EntityUtils.toString(httpresponse.getEntity()));
      System.out.println(httpresponse.getStatusLine());
   }
}

Output

On executing, the above program generates the following output −

{
   "args": {},
   "data": "",
   "files": {},
   "form": {
      "Name": "username",
      "password": "password"
   },
   "headers": {
      "Accept-Encoding": "gzip,deflate",
      "Connection": "close",
      "Content-Length": "31",
      "Content-Type": "application/x-www-form-urlencoded; charset = UTF-8",
      "Host": "httpbin.org",
      "User-Agent": "Apache-HttpClient/4.5.6 (Java/1.8.0_91)"
   },
   "json": null,
   "origin": "117.216.245.180",
   "url": "http://httpbin.org/post"
}
HTTP/1.1 200 OK

Form Login with Cookies

If your form stores cookies, instead of creating default CloseableHttpClient object.

Create a CookieStore object by instantiating the BasicCookieStore class.

//Creating a BasicCookieStore object
BasicCookieStore cookieStore = new BasicCookieStore();

Create a HttpClientBuilder using the custom() method of the HttpClients class.

//Creating an HttpClientBuilder object
HttpClientBuilder clientbuilder = HttpClients.custom();

Set the cookie store to the client builder using the setDefaultCookieStore() method.

//Setting default cookie store to the client builder object
Clientbuilder = clientbuilder.setDefaultCookieStore(cookieStore); 

Build the CloseableHttpClient object using the build() method.

//Building the CloseableHttpClient object
CloseableHttpClient httpclient = clientbuilder1.build();

Build the HttpUriRequest object as specified above by passing execute the request.

If the page stores cookies, the parameters you have passed will be added to the cookie store.

You can print the contents of the CookieStore object where you can see your parameters (along with the previous ones the page stored in case).

To print the cookies, get all the cookies from the CookieStore object using the getCookies() method. This method returns a List object. Using Iterator, print the list objects contents as shown below −

//Printing the cookies
List list = cookieStore.getCookies();

System.out.println("list of cookies");
Iterator it = list.iterator();
if(it.hasNext()) {
   System.out.println(it.next());
}
Advertisements