HtmlUnit小应用,Wifi客户端

学校里的无线网需要网页验证 = = 开机先开浏览器、登验证页面、输密码、点确定 很烦人有木有…… 而且验证页面不能关,这个页面每4分钟向服务器发一次消息 一旦验证页面关了网就断了 %>_<%~

 

转论坛的时候看到了HtmlUnit,心血来潮做了个客户端。

 

先介绍下HtmlUnit,可以把它理解成一个没有界面的浏览器,内置了javascript引擎,可以模拟javascript的运行(比分析页面然后模拟网页向服务器定时发信息的工作量少了很多)。

 

连接部分很简单,代码如下:

 

package WiFiControl;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.util.Iterator;
import javax.swing.JOptionPane;

/**
 * htmlUnit模仿登陆Wifi认证页面
 * 
 * @author sdujq
 * 
 */
public class WifiIndex {

	public static HtmlPage resultPage;
	public static HtmlPage page;
	public static boolean working = false;
	public final static String INDEX = "http://192.168.8.10/portal/";

	/**
	 * 连接Wifi认证页面
	 * 
	 * @throws Exception
	 */
	public static void open() throws Exception {
		WebClient client = new WebClient(BrowserVersion.INTERNET_EXPLORER_8);
		client.waitForBackgroundJavaScript(10000);
		page = client.getPage(INDEX);
		System.gc();
	}

	/**
	 * 登陆Wifi
	 * 
	 * @param uname
	 *            用户名
	 * @param upwd
	 *            密码
	 * @return 是否连接成功
	 * @throws Exception
	 *             囧囧有神
	 */
	public static boolean connect(String uname, String upwd) throws Exception {
		if (page == null) {
			open();
		}
		Iterator<HtmlElement> nodes = page.getHtmlElementDescendants()
				.iterator();
		HtmlInput name = null;
		HtmlInput pwd = null;
		HtmlElement bt = null;
		while (nodes.hasNext()) {
			HtmlElement node = nodes.next();
			String nameArribute = node.getAttribute("name");
			if (nameArribute.equals("username")) {
				name = (HtmlInput) node;
			} else if (nameArribute.equals("password")) {
				pwd = (HtmlInput) node;
			} else if (nameArribute.equals("Submit1")) {
				bt = node;
			}
		}
		name.setValueAttribute(uname);
		pwd.setValueAttribute(upwd);
		resultPage = bt.click();
		Iterator<HtmlElement> elist = resultPage.getHtmlElementDescendants()
				.iterator();
		String res = null;
		while (elist.hasNext()) {
			res = elist.next().getTextContent();
		}
		if (res.contains("You have logged in!")) {
			showMessage("您已经登陆!");
			open();
			return false;
		} else if (res
				.contains("The user does not exist or has not subscribed for this service")) {
			showMessage("用户名或密码错误!");
			open();
			return false;
		}
		working = true;
		return true;
	}
	/**
	 * 显示信息
	 * @param str 信息
	 */
	public static void showMessage(final String str) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				JOptionPane.showMessageDialog(null, str);
			}
		});
	}
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值