1

I currently have code for posting data to a login page that works fine. However, I'm a little lost on how to get the URL of the page after it verifies the login information.

Basically, I have a target url for posting data to, called login.aspx, which then posts it back to itself, verifies the login, and then, if valid, goes to some page.aspx?custId=12345

When I try the getURL method for HTTPUrlConnection after doing the post, it returns the login.aspx URL rather than the page.aspx URL I want. I've tried setFollowRedirects(), once at false and once at true, I've tried getting the Location header (there is none) among other things and nothing worked.

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_USER_NAME = "oipsl";
    private static final String LOGIN_PASSWORD = "poker";

    private static final String TARGET_URL = "http://www.clubspeedtiming.com/prkapolei/login.aspx";

    public static void main (String args[])
    {
        System.out.println("Verifying user in Casa De Chad Database");
        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);

            HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent);
            urlConnection.setFollowRedirects(true);
            System.out.println(urlConnection.getResponseCode());
            System.out.println(urlConnection.getHeaderFields());

            String response = readResponse(urlConnection);

            System.out.println("Successfully made the HTPP POST.");
            System.out.println("Received response is: " + response);
        }
        catch(IOException ioException)
        {
            System.out.println("Problems encountered.");
        }
    }

    /**
     * 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) throws UnsupportedEncodingException
    {
        // Encode the user name and password to UTF-8 encoding standard
        // throws UnsupportedEncodingException
        String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8");
        //Hidden fields also used for verification
        String viewState = URLEncoder.encode("/wEPDwULLTIxMTU1NzMyNDgPZBYCAgMPZBYCAgkPPCsADQBkGAEFAmd2D2dkNyI00Mr5sftsfyEsC6YBMNkj9mI=", "UTF-8");
        String eventvalidation = URLEncoder.encode("/wEWBAK2l8HDAQKQoJfyDwK6z/31BQLCi9reA4vQxgNI61f/aeA7+HYbm+y+7y3g", "UTF-8");

        String content = "tbxRacerName="+encodedLoginUserName+"&__VIEWSTATE="+viewState+"&__EVENTVALIDATION="+eventvalidation;

        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()));
            HttpURLConnection.setFollowRedirects(false);
            urlConnection.connect();
            System.out.println(urlConnection.getHeaderFields());
            System.out.println("URL: "+urlConnection.getURL());
            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
                }
            }

        }
    }
}
oipsl
  • 337
  • 4
  • 17
  • get rid of the DateInputStream - you don't need that. – Bozho Aug 11 '11 at 08:25
  • sorry, where am I looking at? I only see DataOutputStream – oipsl Aug 11 '11 at 08:38
  • yes, my bad - output, not input – Bozho Aug 11 '11 at 08:42
  • Sorry, still not getting it. Any chance you can post some code? – oipsl Aug 11 '11 at 09:55
  • I will, but I'm busy right now. I hope I'll manage till the end of the day to provide something simple – Bozho Aug 11 '11 at 10:43
  • @Bozho Hi again, just checking if you can still help me out? I know you're busy but I still dont have an answer – oipsl Aug 16 '11 at 04:11
  • I can, but I'm on a one week vacation. But let me give you a link – Bozho Aug 16 '11 at 06:19
  • See if this helps http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests/2793153#2793153 – Bozho Aug 16 '11 at 06:22
  • ok i figured out what i was doing wrong here- when I encoded the __VIEWSTATE and __EVENTVALIDATION variables using UTF-8, some of the characters in the value were changed, which is why it didn't redirect properly since the values were wrong. So I didn't encode it and it seemed to work fine. However, is there a potential problem/error I could encounter since I'm not encoding my POST data before sending it? – oipsl Aug 16 '11 at 10:00
  • good question. I think you should encode it (use `URLEncoder.encode(..)`) – Bozho Aug 16 '11 at 10:05

1 Answers1

0

If there is no Location header, and followRedirects is true (it's true by default), it means there is no redirect. Might be server-side redirect (forward), which doesn't change the browser URL. When you login with a browser do you see the page.aspx?custId=12345 in the address bar?

Bozho
  • 554,002
  • 136
  • 1,025
  • 1,121
  • yeah, if i login through a browser, it takes me to that page.aspx URL, and I'm pretty sure it posts it back to login.aspx looking at the "action" tag in the
    html, and then does something to bring me to the page.aspx url
    – oipsl Aug 11 '11 at 06:45
  • http://www.clubspeedtiming.com/prkapolei/login.aspx you can use my login "oipsl" if you need to – oipsl Aug 11 '11 at 07:33
  • The location header is used: Location: http://www.clubspeedtiming.com/prkapolei/RacerHistory.aspx?CustID=1047060 so please show us your code, it should be some minor mistake – Bozho Aug 11 '11 at 07:37
  • ok posted my code. i printed the header contents and still dont see the Location header there, and when I call getUrl() i get the login.aspx. disregard the "poker" password variable, im reusing code from another sample – oipsl Aug 11 '11 at 07:59