html页面无法连接,HTML单元 - 使用表单登录到安全网站 - 无法在表单后连接到页面...

我是java htmlunit的新手,所以任何帮助都将不胜感激 - 提前致谢。

我正在尝试使用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部分运行代码错误:

在contentWeb.main的线程“main”> java.lang.NullPointerException中的异常(contentWeb.java:26)

返回。

我是java htmlunit的新手,所以任何帮助都会非常感激。

提前谢谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值