HtmlUnit Session Management
Asked Answered
V

2

5

I'm trying to login to Facebook page using HtmlUnit and view its HTML content. I'm trying to fill up the login credentials through HtmlUnit but I don't see the session being carried when the submit button is clicked.

Couldnt find much content on htmlunit session management classes. I have also attached the code that I'm currently using to attempt this problem. Any help appreciated!

WebClient webClient = new WebClient();
HtmlPage page1 = webClient.getPage("https://www.facebook.com");
List<HtmlForm> listF = page1.getForms();
HtmlForm form = null;
for(int i=0; i<listF.size(); i++)
{
    if(listF.get(i).getId().equals("login_form"))
    {
        form = listF.get(i);
        }
}
HtmlTextInput uName = form.getInputByName("email");
HtmlPasswordInput passWord = form.getInputByName("pass");
HtmlSubmitInput button = form.getInputByValue("Log In");
uName.setValueAttribute(FACEBOOK_UNAME);
passWord.setValueAttribute(FACEBOOK_PASS);
HtmlPage page2 = button.click();
Vinegar answered 22/10, 2012 at 5:21 Comment(0)
V
10

Found the answer. Just enabled cookies before starting to get webpages. It works. Added the below piece of code

WebClient webClient = new WebClient();
CookieManager cookieMan = new CookieManager();
cookieMan = webClient.getCookieManager();
cookieMan.setCookiesEnabled(true);
Vinegar answered 26/10, 2012 at 11:5 Comment(1)
It looks like you also get that setting by default when you instantiate the webclient as a browser version: WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_11);Spineless
V
0

Another advice is if you are trying to restore HTTP session in HtmlUnit, instead of using webClient.getCookieManager().addCookie(cookie);, use this instead :

webClient.addCookie("cookieName=cookieValue", URL, null);
Verdun answered 22/4, 2019 at 18:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.