cookieI had this post on how to login to sites using Java’s URL and HttpURLConnection classes and how there is no need to manually store a cookie’s information and pass it to every other URL you intend to visit that requires a login if it cannot find the cookie information. This neat Cookie utility by Saar Machtinger handles all storing of cookie information after you log in to a site. It only needs to read the the contents of the HttpURLConnection variable after it has successfuly posted a request to login.

Then, once you have the CookieTool variable in hand with the cookie information like session id among others, you can access any url of that certain site which you logged in to. To do so, simply do this (ct is the CookieTool variable).

This is the CookieTool class by the way.

Last weekend, I had a job interview with regards to Javascript. I was asked if Javascript can pass values from one page to another. All I said was if it is possible, I can look it up in Google. When my initial exam started, I looked it up if it is indeed possible. And voila, cookies were mentioned. I have never used cookies in Javascript before so I totally had no idea until I looked it up. The best functions for me in setting and retrieving cookies in Javascript are the functions found in a W3Schools column.

Using these two functions below, you can set and get a cookie (depending on the expiry value you specify).

I came across someone else’s code a long time ago and I thought someone else may find this useful since this class has been part of my library whenever my program involves cookies. It is a class by Saar Machtinger.

Say for example you wish to log in to a site and want to keep your session intact when you access the site’s other pages (since they require you to be logged in). To use this class, do the following

We need a URL connection to set which site we want to log in to. Then specify the username and password and use the OutputStreamWriter’s write() method to emulate an HTML Form post action. The last method call, viewAllCookies() displays all data that are stored in the cookie. Please remember that the parameters passed like username and password are not the same in all sites. You should check the site’s HTML FORM tags and see what other hidden fields are included that could possible be needed in order for you to be able to logged in properly.

If you wish to access other links of the site that require you to be logged in, just use the CookieTool object ct like this

You can then use the HttpURLConnection’s getInputStream() method to get the InputStream and use it to retrieve the contents of the HTML page. Getting the contents of the InputStream and storing it in a String object is another story. There is a nifty code that I use to do this (I forgot who coded this). Just go here.

Related Posts Plugin for WordPress, Blogger...