Java Keeping Track Of Cookies

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.

public class CookieTool {
 
  static Hashtable theCookies = new Hashtable();
 
  /**
  * Send the Hashtable (theCookies) as cookies, and write them to
  *  the specified URLconnection
  *
  * @param   urlConn  The connection to write the cookies to.
  * @param   printCookies  Print or not the action taken.
  *
  * @return  The urlConn with the all the cookies in it.
  */
  public URLConnection writeCookies(URLConnection urlConn, boolean printCookies){
    String cookieString = "";
    Enumeration keys = theCookies.keys();
 
    while (keys.hasMoreElements()) {
      String key = (String)keys.nextElement();
      cookieString += key + "=" + theCookies.get(key);
      if (keys.hasMoreElements()) cookieString += "; ";
    }
 
    urlConn.setRequestProperty("Cookie", cookieString);
 
    if (printCookies) System.out.println("Wrote cookies:\n   " + cookieString+"\n");
 
    return urlConn;
  }
 
  /**
  * Read cookies from a specified URLConnection, and insert them
  *   to the Hashtable
  *  The hashtable represents the Cookies.
  *
  * @param   urlConn  the connection to read from
  * @param   printCookies  Print the cookies or not, for debugging
  * @param   reset  Clean the Hashtable or not
  */
 
  public void readCookies(URLConnection urlConn, boolean printCookies, boolean reset) {
    if (reset) theCookies.clear();
    int i=1;
    String hdrKey;
    String hdrString;
    String aCookie;
 
    while ((hdrKey = urlConn.getHeaderFieldKey(i)) != null) {
      if (hdrKey.equals("Set-Cookie")) {
        hdrString = urlConn.getHeaderField(i);
        StringTokenizer st = new StringTokenizer(hdrString,",");
 
        while (st.hasMoreTokens()) {
          String s = st.nextToken();
          aCookie = s.substring(0, s.indexOf(";"));
          // aCookie = hdrString.substring(0, s.indexOf(";"));
          int j = aCookie.indexOf("=");
 
          if (j != -1) {
            if (!theCookies.containsKey(aCookie.substring(0, j))) {
               // if the Cookie do not already exist then when keep it,
               // you may want to add some logic to update 
               // the stored Cookie instead. thanks to rwhelan
               theCookies.put(aCookie.substring(0, j),aCookie.substring(j + 1));
 
              if (printCookies) {
                System.out.println("Reading Key: "  + aCookie.substring(0, j));
                System.out.println("        Val: " + aCookie.substring(j + 1));
              }
            }
          }
        }
      }
      i++;
    }
  }
 
  /**
  * Display all the cookies currently in the HashTable
  *
  */
  public void viewAllCookies() {
    System.out.println("All Cookies are:");
    Enumeration keys = theCookies.keys();
    String key;
    while (keys.hasMoreElements()) {
      key = (String)keys.nextElement();
      System.out.println("   " + key + "=" + theCookies.get(key));
    }
  }
 
  /**
  * Display the current cookies in the URLConnection,
  *    searching for the: "Cookie" header
  *
  * This is Valid only after a writeCookies operation.
  *
  * @param   urlConn  The URL to print the associates cookies in.
  */
  public void viewURLCookies(URLConnection urlConn) {
    System.out.print("Cookies in this URLConnection are:\n");
    System.out.println(urlConn.getRequestProperty("Cookie"));
  }
 
  /**
  * Add a specific cookie, by hand, to the HastTable of the Cookies
  *
  * @param   _key  The Key/Name of the Cookie
  * @param   _val  The Calue of the Cookie
  * @param   printCookies  Print or not the result
  */
  public void addCookie(String _key, String _val, boolean printCookies) {
    if (!theCookies.containsKey(_key)) {
      theCookies.put(_key, _val);
      if (printCookies){
        System.out.println("Adding Cookie: ");
        System.out.println("   " + _key + " = " + _val);
      }
    }
  }
}

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

URL url = new URL("URL_SITE_HERE");
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.setDoOutput(true);
 
String data = "username=" + YOUR_USERNAME + "password=" + YOUR_PASSWORD;
 
OutputStreamWriter wr = new OutputStreamWriter(httpcon.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
httpcon.setInstanceFollowRedirects(false);
 
CookieTool ct = new CookieTool();
ct.readCookies(httpcon, false, false);
httpcon.disconnect();
 
ct.viewAllCookies();

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

URL url = new URL("LINK_HERE");
HttpURLConnection httpcon = IMDBTool.getCookiedHttpURLConnection(ct, url);
ct.readCookies(httpcon, false, false);

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.

Like what you see? Buy me a cup of coffee. Or subscribe to my feeds.


(No Ratings Yet)
 Loading ...

Javascript Create A Hyperlink Element

Creating a hyperlink element using Javascript is pretty simple. Do the following. Notice, that the hyperlink element contains two text ‘click me’ that’s been set twice. This is because IE only accepts its proprietary innerText property to set a hyperlink’s text while other browsers use textContent. To set a CSS class name, you need to use the className attribute because the class property is a reserved word in Javascript. You can either use it as element.classname = 'class_name' or element.setAttribute('className', 'class_name');

<div id="div"></div>
<script>
div = document.getElementById('div');
 
a = document.createElement('a');
a.innerText = 'click me';
a.textContent = 'click me';
a.href = 'javascript://';
a.setAttribute('className', 'more_right');
a.setAttribute('onclick', 'alert("clicked");');
 
div.appendChild(a);
</script>

Like what you see? Buy me a cup of coffee. Or subscribe to my feeds.


(No Ratings Yet)
 Loading ...

Javascript Get Browser

Getting the browser that you are using using Javascript can be important in some cases. Like when reading or setting an element’s property, browsers like IE and Firefox both have different ways to do them. Take for example creating a hyperlink using Javascript. To create the text of the hyperlink, IE uses its proprietary innerText property while Firefox uses textContent (although the specific browser will just ignore the property that it cannot recognize, I feel it’s nice to use browser detection to fully ignore the property even if no error will be thrown). Using the function below can be pretty useful in doing conditional statements on which property to apply to an element. The function is custom made, you can modify it if you wish since my only concern was having to know if the browser was IE or not.

function getBrowser() {
  var sBrowser = navigator.userAgent;
  if (sBrowser.toLowerCase().indexOf('msie') > -1) return 'ie';
  else if (sBrowser.toLowerCase().indexOf('firefox') > -1) return 'firefox';
  else return 'mozilla';
}

Like what you see? Buy me a cup of coffee. Or subscribe to my feeds.


(1 votes, average: 4.00 out of 5)
 Loading ...

Reversi For iTouch By Big Bang Games, Freeverse

When the iPhone firmware version 2 was released, I was pretty excited about it because Apple finally let developers create games for the device. Before it was only restricted to users being able to use applications that Apple provided. Now, there are lots of games created and one of the games that I anticipated is the Reversi game. It took very long for this kind of game to be cracked but finally it’s been done. Big Bang Games is a collection of classic games like Chess, 4 In A Row, Backgammon, Checkers, Mancala (Sungka in Filipino) and Reversi. These are the same set of games that you see when you have Mac OS installed in your laptop or desktop. I never get bored with Reversi, even if I win 99.9% of the time lolz. I will not explain how each game works since they are classic games and for sure most of you know how they are played or at least have an idea about them. I wished they included a WIFI feature so that you can multiplay with another player. Hopefully, their next version will have this feature (if there will be a next version). The AI (Artificial Intelligence) is decent, although not better than the Nintendo Family Computer version of it (Othello). I’m not complaining though. This is the very first game that I tap right away to play when I get bored. My first wish was granted. I hope my next wishes would become realities. I would love to see a Text Twist, Mummy Maze and those famous Big Fish Games available for the iPhone/iTouch.

Like what you see? Buy me a cup of coffee. Or subscribe to my feeds.


(No Ratings Yet)
 Loading ...