日期:2014-05-17  浏览次数:20883 次

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);
			}
		});
	}
}
?