Jun 20, 2013

Java: How to get cookie from HttpURLConnection

Here the simple code to get the site response cookie.

URL urlReq = new URL("http://www.google.com");

conn = (HttpURLConnection) urlReq.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(8000);
conn.setConnectTimeout(8000);

// Start building other http request parameter
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:21.0) Gecko/20100101 Firefox/21.0");
conn.setRequestProperty("Accept-Language","en-us,en;q=0.5");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
conn.setRequestProperty("Connection", "close");

conn.setDoOutput(true);
conn.setDoInput(true);

conn.connect();
resCode = conn.getResponseCode(); 
if (resCode==HttpURLConnection.HTTP_OK){
 for(Map.Entry<String, List<String>> headers : conn.getHeaderFields().entrySet()){
 if (headers.getKey().equals("set-cookie")){
      logger.info("\t==>"+headers.getKey());
      for(String hval : headers.getValue()){
       logger.info("\t\t==>"+hval);
      }
 }else{
  logger.info("\t==>"+headers.getKey() +" = "+conn.getHeaderField(headers.getKey()));
 }
}





You can also use
conn.getHeaderField("Set-Cookie")
However, the bad thing is you can one get one cookie, I suggest to use
conn.getHeaderFields()

Happy Reading

Jun 5, 2013

How to determine the user browser version in html?

Since this code, is only application in IE(Internet Explorer). Maybe the question is, How to determine the browser version in html.

This this check is the user user IE Browser, whatever the version.
<!--[if IE]>
Place content here to target all Internet Explorer users.
<![endif]-->

This was opposite behavior on the first item. "This is only run when the browser is NOT Internet Explorer".
<![if !IE]>
Place content here to target all users not using Internet Explorer.
<![endif]>

This will run if the browser version is greater than or equal to 8.
<!--[if gte IE 8]>
Place content here to target users of Internet Explorer 8 or higher.
<![endif]-->

A similar example above that only runs when the browser version is less than 7 (i.e. 6 or lower).
<!--[if lt IE 7]>
Place content here to target users of Internet Explorer 6 or lower (less than 7).
<![endif]-->

Conclusion:
The code/conditions are only run when running on IE browser, otherwise the browser will detect/treat as normal comment.