我是一个java htmlunit的新手,所以任何帮助将不胜感激 - 在此先感谢。HTML单元 - 使用窗体登录到安全网站 - 无法连接到页面后形式
我试图登录到了通过使用到的HtmlUnit镜像网页浏览器的行为上的网页提交用户名和密码的形式与用户名和密码验证保护的网页。该网站本身具有基于表单的授权。
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 to submit user and password credentials
//and mirrors how a login button would be clicked on a webpage:
public class submitForm {
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient();
// Get the first page
HtmlPage page1 = (HtmlPage) webClient.getPage("http://cmdbjr/frameset.php?ci_name=&ci_id=&ci_type=");
// Get the form that we are dealing with and within that form,
// find the submit button and the field that we want to change.
HtmlForm form = page1.getFormByName("loginform");
// Enter login and passwd
form.getInputByName("user_id").setValueAttribute("#####");
form.getInputByName("password").setValueAttribute("#####");
// Click "Sign In" button/link
page1 = (HtmlPage) form.getInputByValue("Log In").click();
// I added the cookie section but this returns a null pointer exception
Set cookie = webClient.getCookieManager().getCookies();
if(cookie != null){
Iterator i = cookie.iterator();
while (i.hasNext()) {
webClient.getCookieManager().addCookie(i.next());
}
}
// Get page as Html
String htmlBody = page1.getWebResponse().getContentAsString();
// Save the response in a file
String filePath = "c:/temp/test_out.html";
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath)));
bw.write(htmlBody);
bw.close();
// Change the value of the text field
// userField.setValueAttribute("alwalsh");
// passwordField.setValueAttribute("1REland6");
// Now submit the form by clicking the button and get back the second page.
// final HtmlPage page2 = button.click();
webClient.closeAllWindows();
}
}
如果没有我的代码中的Cookie部分运行的代码我试图达到其 是登录页面后不出现错误页面的页面显示说我没有连接到互联网。
如果代码是与cookie部分运行错误:
Exception in thread "main" >java.lang.NullPointerException at contentWeb.main(contentWeb.java:26)
返回。
我是新来的Java这样的HtmlUnit任何帮助都将不胜感激。 在此先感谢。
2012-03-07
Alan