htmlunit - HTML Unit - login to secure website using form - can't connect to page after form -
i'm newbie java htmlunit appreciated - in advance.
i'm trying login webpage protected username , password authentication submitting username , password form on webpage using htmlunit mirror actions of web browser. website has form based authorisation.
import java.io.bufferedwriter; import java.io.file; import java.io.filewriter; import java.util.iterator; import java.util.set; //import htmlunit classes import com.gargoylesoftware.htmlunit.webclient; import com.gargoylesoftware.htmlunit.html.htmlform; import com.gargoylesoftware.htmlunit.html.htmlpage; import com.gargoylesoftware.htmlunit.html.htmlsubmitinput; import com.gargoylesoftware.htmlunit.html.htmltextinput; import com.gargoylesoftware.htmlunit.util.cookie; //this class attempts submit user , password credentials //and mirrors how login button clicked on webpage: public class submitform { public static void main(string[] args) throws exception { webclient webclient = new webclient(); // first page htmlpage page1 = (htmlpage) webclient.getpage("http://cmdbjr/frameset.php?ci_name=&ci_id=&ci_type="); // form dealing , within form, // find submit button , field want change. htmlform form = page1.getformbyname("loginform"); // enter login , passwd form.getinputbyname("user_id").setvalueattribute("#####"); form.getinputbyname("password").setvalueattribute("#####"); // click "sign in" button/link page1 = (htmlpage) form.getinputbyvalue("log in").click(); // added cookie section returns null pointer exception set<cookie> cookie = webclient.getcookiemanager().getcookies(); if(cookie != null){ iterator<cookie> = cookie.iterator(); while (i.hasnext()) { webclient.getcookiemanager().addcookie(i.next()); } } // page html string htmlbody = page1.getwebresponse().getcontentasstring(); // save response in file string filepath = "c:/temp/test_out.html"; bufferedwriter bw = new bufferedwriter(new filewriter(new file(filepath))); bw.write(htmlbody); bw.close(); // change value of text field // userfield.setvalueattribute("alwalsh"); // passwordfield.setvalueattribute("1reland6"); // submit form clicking button , second page. // final htmlpage page2 = button.click(); webclient.closeallwindows(); } }
if run code without cookie section of code page trying reach after login page doesn't appear error page appears saying i'm not connected internet.
if code run cookie section error:
exception in thread "main" >java.lang.nullpointerexception @ contentweb.main(contentweb.java:26)
is returned.
i'm new java htmlunit @ appreciated. in advance.
i replicated example yahoo mail login credentials , worked. however, added : webclient.setthrowexceptiononscripterror(false);
ignore exceptions on script errors.
Comments
Post a Comment