English 中文(简体)
Form-Based Login
  • 时间:2024-09-17

Apache HttpCpent - Form-Based Login


Previous Page Next Page  

Using the HttpCpent pbrary 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 HttpCpent object

The createDefault() method of the HttpCpents class returns an object of the class CloseableHttpCpent, which is the base implementation of the HttpCpent interface. Using this method, create an HttpCpent object −

CloseableHttpCpent httpCpent = HttpCpents.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 CloseableHttpCpent 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 = httpcpent.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.cpent.methods.HttpUriRequest;
import org.apache.http.cpent.methods.RequestBuilder;
import org.apache.http.impl.cpent.CloseableHttpCpent;
import org.apache.http.impl.cpent.HttpCpents;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;

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

      //Creating CloseableHttpCpent object
      CloseableHttpCpent httpcpent = HttpCpents.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 = httpcpent.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": "apppcation/x-www-form-urlencoded; charset = UTF-8",
      "Host": "httpbin.org",
      "User-Agent": "Apache-HttpCpent/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 CloseableHttpCpent object.

Create a CookieStore object by instantiating the BasicCookieStore class.

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

Create a HttpCpentBuilder using the custom() method of the HttpCpents class.

//Creating an HttpCpentBuilder object
HttpCpentBuilder cpentbuilder = HttpCpents.custom();

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

//Setting default cookie store to the cpent builder object
Cpentbuilder = cpentbuilder.setDefaultCookieStore(cookieStore); 

Build the CloseableHttpCpent object using the build() method.

//Building the CloseableHttpCpent object
CloseableHttpCpent httpcpent = cpentbuilder1.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 pst objects contents as shown below −

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

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