How to get cookies from a headless browser provided by HtmlUnit in Java?

4.7k Views Asked by At

I am using HtmlUnit Driver for generating a headless browser. I need the cookie information run the tests ahead. While i am able to inspect the elements i am unable to derive the cookie informations. Please help.

3

There are 3 best solutions below

0
On BEST ANSWER

You can get Cookies information from HtmlUnitDriver using driver.manage().getCookies(); (driver is instance of HtmlUnitDriver).

Here is the sample Java code that prints Cookie name and its value:

Set<Cookie> allCookies = driver.manage().getCookies();
for (Cookie cookie : allCookies) {
System.out.println(String.format( "%s -> %s" , cookie.getName(), cookie.getValue()));
}
0
On

Additionally if you are aware of the name of Cookie for which you want to get value , you can directly use method , getCookieName.

Method Name: getCookieNamed(java.lang.String name)
Syntax: driver.manage().getCookieNamed(CookieName);
Purpose: To Get a cookie with a given name.
Arguments: CookieName- the name of the cookie
Returns: It will return the cookie value for the name specified, or null if no cookie found with the
given name

0
On

Here is what i used.

Cookie cookie = new Cookie("key", "value");
      driver.manage().addCookie(cookie);
      Set<Cookie> allCookies = driver.manage().getCookies();
      for (Cookie loadedCookie : allCookies) {
        System.out.println(String.format("%s -> %s", loadedCookie.getName(),  loadedCookie.getValue()));
        }