Logging in to a site using pure Java code is possible with just the URL and HttpURLConnection classes. First, you need to know the action URL of the <form> tag in a website that you wish to login to. Next, look for all input field tags within the <form> tag because they will be needed to be passed as parameters when you submit to the form URL, e.g. in this case, logging in to the site. Every input field with a name attribute should be passed just to be sure. Suppose we have a sample form that looks like this.
<input type="text" name="username" size="20"/><br/>
<input type="text" name="password" size="20"/><br/>
<input type="submit" value="login"/>
To log in using Java programmatically, use the following code.
URL url = new URL("http://www.mydomain.com/login.jsp");
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
String data = "username=MYUSERNAME&password=MYPASSWORD";
OutputStreamWriter wr = new OutputStreamWriter(httpcon.getOutputStream());
CookieTool ct = new CookieTool();
ct.readCookies(httpcon, false, false);
That is it. Any other page you wish to go to, just use the CookieTool variable which contains everything that the generated cookie contains like session id. What is CookieTool exactly for? Go here to find more about how to use this neat Cookie utility to store your cookie sessions so that which page you would go to the site that requires a login, you do not need to log in again because the cookie information is stored in the CookieTool variable.