Full Code Listing - Login to a website using HTTP POST in Java
This is a full code listing of a Java program thatcan log into a website using HTTP post. This jav program is available for download as well along with a sample PHP login form script is also provided. You will also find the URL of the live login script that you use to test this program.
Table of Contents [hide]
Full Code Listing
/**
* Copyright 2008 www.1your.com
*/
package com.oneyour.net;
import java.net.*;
import java.io.*;
public class LogInByHttpPost
{
private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
private static final String LOGIN_ACTION_NAME = "Login";
private static final String LOGIN_USER_NAME_PARAMETER_NAME = "user_name";
private static final String LOGIN_PASSWORD_PARAMETER_NAME = "user_pass";
private static final String LOGIN_USER_NAME = "test";
private static final String LOGIN_PASSWORD = "test";
private static final String TARGET_URL = "http://www.1your.com/drupal/sample_login.php";
public static void main (String args[])
{
System.out.println("About to run the 'LogInByHttpPost' downloaded from www.1Your.com");
LogInByHttpPost httpUrlBasicAuthentication = new LogInByHttpPost();
httpUrlBasicAuthentication.httpPostLogin();
}
/**
* The single public method of this class that
* 1. Prepares a login message
* 2. Makes the HTTP POST to the target URL
* 3. Reads and returns the response
*
* @throws IOException
* Any problems while doing the above.
*
*/
public void httpPostLogin ()
{
try
{
// Prepare the content to be written
// throws UnsupportedEncodingException
String urlEncodedContent = preparePostContent(LOGIN_USER_NAME, LOGIN_PASSWORD);
HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent);
String response = readResponse(urlConnection);
System.out.println("Successfully made the HTPP POST.");
System.out.println("Recevied response is: '/n" + response + "'");
System.out.println("/n Hope you found the article and this sample program useful./nPlease leave your feed back at www.1your.com and support us.");
}
catch(IOException ioException)
{
System.out.println("Problems encounterd.");
}
}
/**
* Using the given username and password, and using the static string variables, prepare
* the login message. Note that the username and password will encoded to the
* UTF-8 standard.
*
* @param loginUserName
* The user name for login
*
* @param loginPassword
* The password for login
*
* @return
* The complete login message that can be HTTP Posted
*
* @throws UnsupportedEncodingException
* Any problems during URL encoding
*/
private String preparePostContent(String loginUserName, String loginPassword) throws UnsupportedEncodingException
{
// Encode the user name and password to UTF-8 encoding standard
// throws UnsupportedEncodingException
String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8");
String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8");
String content = "login=" + LOGIN_ACTION_NAME +" &" + LOGIN_USER_NAME_PARAMETER_NAME +"="
+ encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;
return content;
}
/**
* Makes a HTTP POST to the target URL by using an HttpURLConnection.
*
* @param targetUrl
* The URL to which the HTTP POST is made.
*
* @param content
* The contents which will be POSTed to the target URL.
*
* @return
* The open URLConnection which can be used to read any response.
*
* @throws IOException
*/
public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException
{
HttpURLConnection urlConnection = null;
DataOutputStream dataOutputStream = null;
try
{
// Open a connection to the target URL
// throws IOException
urlConnection = (HttpURLConnection)(new URL(targetUrl).openConnection());
// Specifying that we intend to use this connection for input
urlConnection.setDoInput(true);
// Specifying that we intend to use this connection for output
urlConnection.setDoOutput(true);
// Specifying the content type of our post
urlConnection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);
// Specifying the method of HTTP request which is POST
// throws ProtocolException
urlConnection.setRequestMethod("POST");
// Prepare an output stream for writing data to the HTTP connection
// throws IOException
dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
// throws IOException
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();
return urlConnection;
}
catch(IOException ioException)
{
System.out.println("I/O problems while trying to do a HTTP post.");
ioException.printStackTrace();
// Good practice: clean up the connections and streams
// to free up any resources if possible
if (dataOutputStream != null)
{
try
{
dataOutputStream.close();
}
catch(Throwable ignore)
{
// Cannot do anything about problems while
// trying to clean up. Just ignore
}
}
if (urlConnection != null)
{
urlConnection.disconnect();
}
// throw the exception so that the caller is aware that
// there was some problems
throw ioException;
}
}
/**
* Read response from the URL connection
*
* @param urlConnection
* The URLConncetion from which the response will be read
*
* @return
* The response read from the URLConnection
*
* @throws IOException
* When problems encountered during reading the response from the
* URLConnection.
*/
private String readResponse(HttpURLConnection urlConnection) throws IOException
{
BufferedReader bufferedReader = null;
try
{
// Prepare a reader to read the response from the URLConnection
// throws IOException
bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String responeLine;
// Good Practice: Use StringBuilder in this case
StringBuilder response = new StringBuilder();
// Read untill there is nothing left in the stream
// throws IOException
while ((responeLine = bufferedReader.readLine()) != null)
{
response.append(responeLine);
}
return response.toString();
}
catch(IOException ioException)
{
System.out.println("Problems while reading the response");
ioException.printStackTrace();
// throw the exception so that the caller is aware that
// there was some problems
throw ioException;
}
finally
{
// Good practice: clean up the connections and streams
// to free up any resources if possible
if (bufferedReader != null)
{
try
{
// throws IOException
bufferedReader.close();
}
catch(Throwable ignore)
{
// Cannot do much with exceptions doing clean up
// Ignoring all exceptions
}
}
}
}
}
* Copyright 2008 www.1your.com
*/
package com.oneyour.net;
import java.net.*;
import java.io.*;
public class LogInByHttpPost
{
private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
private static final String LOGIN_ACTION_NAME = "Login";
private static final String LOGIN_USER_NAME_PARAMETER_NAME = "user_name";
private static final String LOGIN_PASSWORD_PARAMETER_NAME = "user_pass";
private static final String LOGIN_USER_NAME = "test";
private static final String LOGIN_PASSWORD = "test";
private static final String TARGET_URL = "http://www.1your.com/drupal/sample_login.php";
public static void main (String args[])
{
System.out.println("About to run the 'LogInByHttpPost' downloaded from www.1Your.com");
LogInByHttpPost httpUrlBasicAuthentication = new LogInByHttpPost();
httpUrlBasicAuthentication.httpPostLogin();
}
/**
* The single public method of this class that
* 1. Prepares a login message
* 2. Makes the HTTP POST to the target URL
* 3. Reads and returns the response
*
* @throws IOException
* Any problems while doing the above.
*
*/
public void httpPostLogin ()
{
try
{
// Prepare the content to be written
// throws UnsupportedEncodingException
String urlEncodedContent = preparePostContent(LOGIN_USER_NAME, LOGIN_PASSWORD);
HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent);
String response = readResponse(urlConnection);
System.out.println("Successfully made the HTPP POST.");
System.out.println("Recevied response is: '/n" + response + "'");
System.out.println("/n Hope you found the article and this sample program useful./nPlease leave your feed back at www.1your.com and support us.");
}
catch(IOException ioException)
{
System.out.println("Problems encounterd.");
}
}
/**
* Using the given username and password, and using the static string variables, prepare
* the login message. Note that the username and password will encoded to the
* UTF-8 standard.
*
* @param loginUserName
* The user name for login
*
* @param loginPassword
* The password for login
*
* @return
* The complete login message that can be HTTP Posted
*
* @throws UnsupportedEncodingException
* Any problems during URL encoding
*/
private String preparePostContent(String loginUserName, String loginPassword) throws UnsupportedEncodingException
{
// Encode the user name and password to UTF-8 encoding standard
// throws UnsupportedEncodingException
String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8");
String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8");
String content = "login=" + LOGIN_ACTION_NAME +" &" + LOGIN_USER_NAME_PARAMETER_NAME +"="
+ encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;
return content;
}
/**
* Makes a HTTP POST to the target URL by using an HttpURLConnection.
*
* @param targetUrl
* The URL to which the HTTP POST is made.
*
* @param content
* The contents which will be POSTed to the target URL.
*
* @return
* The open URLConnection which can be used to read any response.
*
* @throws IOException
*/
public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException
{
HttpURLConnection urlConnection = null;
DataOutputStream dataOutputStream = null;
try
{
// Open a connection to the target URL
// throws IOException
urlConnection = (HttpURLConnection)(new URL(targetUrl).openConnection());
// Specifying that we intend to use this connection for input
urlConnection.setDoInput(true);
// Specifying that we intend to use this connection for output
urlConnection.setDoOutput(true);
// Specifying the content type of our post
urlConnection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);
// Specifying the method of HTTP request which is POST
// throws ProtocolException
urlConnection.setRequestMethod("POST");
// Prepare an output stream for writing data to the HTTP connection
// throws IOException
dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
// throws IOException
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();
return urlConnection;
}
catch(IOException ioException)
{
System.out.println("I/O problems while trying to do a HTTP post.");
ioException.printStackTrace();
// Good practice: clean up the connections and streams
// to free up any resources if possible
if (dataOutputStream != null)
{
try
{
dataOutputStream.close();
}
catch(Throwable ignore)
{
// Cannot do anything about problems while
// trying to clean up. Just ignore
}
}
if (urlConnection != null)
{
urlConnection.disconnect();
}
// throw the exception so that the caller is aware that
// there was some problems
throw ioException;
}
}
/**
* Read response from the URL connection
*
* @param urlConnection
* The URLConncetion from which the response will be read
*
* @return
* The response read from the URLConnection
*
* @throws IOException
* When problems encountered during reading the response from the
* URLConnection.
*/
private String readResponse(HttpURLConnection urlConnection) throws IOException
{
BufferedReader bufferedReader = null;
try
{
// Prepare a reader to read the response from the URLConnection
// throws IOException
bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String responeLine;
// Good Practice: Use StringBuilder in this case
StringBuilder response = new StringBuilder();
// Read untill there is nothing left in the stream
// throws IOException
while ((responeLine = bufferedReader.readLine()) != null)
{
response.append(responeLine);
}
return response.toString();
}
catch(IOException ioException)
{
System.out.println("Problems while reading the response");
ioException.printStackTrace();
// throw the exception so that the caller is aware that
// there was some problems
throw ioException;
}
finally
{
// Good practice: clean up the connections and streams
// to free up any resources if possible
if (bufferedReader != null)
{
try
{
// throws IOException
bufferedReader.close();
}
catch(Throwable ignore)
{
// Cannot do much with exceptions doing clean up
// Ignoring all exceptions
}
}
}
}
}
Live PHP Login script
You can point this program to the live login form PHP script which can be found at http://www.1your.com/drupal/sample_login.php. This script is available for downlaod as well.








Comments
Discussions
Please check this discussion relating to this article and feel free to even post. http://www.1your.com/drupal/node/171
Is it loging into the site
Hi
I have similat use case and I tried the same step but when post the URL, I'm not able to login to the site but it return back the same login page instead.
Can you please confirm whether you were able to login if you pass the correct user name and password in the login
regards,
Sri
Make sure you populate all required form fields.
I had to add a "action=Login" field that is the form action.
Once I added that it all worked perfectly.
I also made a connection over HTTPS by adding the following:
TrustManager[] tm = {new RelaxedX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory sf = sslContext.getSocketFactory();
urlConnection.setSSLSocketFactory(sf);
/*********************************************
* Connection security setup
**********************************************/
class RelaxedX509TrustManager implements X509TrustManager
{
public boolean isClientTrusted(java.security.cert.X509Certificate[] chain){ return true; }
public boolean isServerTrusted(java.security.cert.X509Certificate[] chain){ return true; }
public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String input) {}
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String input) {}
}
Don't forget to import the following
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
NOT WORKING
That's not working ... tried it on www.bitgamer.com .. can anyone please shed some light on wut to put in here
private static final String LOGIN_ACTION_NAME = "Login";
in your example i've used whatever value for the above variable and they all worked even if empty string, also the target URL should that be the URL of the home page itself like "http://www.bitgamer.com/login.php" or the action of the login form itself which is for bitgamer is action="takelogin.php" ...
Please anyone make this little clear cuz i've tried in so many ways and it's not working ... always giving me the login page html code as response
Thank you
Post new comment