欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

htmlunit模拟sso登陆

程序员文章站 2022-07-14 08:00:12
...

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.TextPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.util.NameValuePair;

public class SSO1 {
public static void main(String[] args)
throws FailingHttpStatusCodeException, MalformedURLException,
IOException {
// 创建浏览器,可以选择IE、FF等等
WebClient client = new WebClient(BrowserVersion.FIREFOX_3_6);

// 获取某网站页面
URL url = new URL("http://xxxxxx.com:8082/rest/tickets");
WebRequest webRequest = new WebRequest(url, HttpMethod.POST);
List<NameValuePair> reqParam = new ArrayList<NameValuePair>();

reqParam.add(new NameValuePair("username", "xxxx"));
reqParam.add(new NameValuePair("password", "xxxx"));

webRequest.setRequestParameters(reqParam);
HtmlPage mypage = (HtmlPage) client.getPage(webRequest);
mypage.getElementByName("service").setAttribute("value",
"http://zzzzz.com/bbbb/index.action");

HtmlForm form = mypage.getForms().get(0);
TextPage page = ((HtmlSubmitInput) form.getElementsByAttribute("input",
"type", "submit").get(0)).click();

String ticket = page.getContent();

url = new URL("http://zzzzz.com/bbbb/index.action");
webRequest = new WebRequest(url, HttpMethod.POST);

reqParam = new ArrayList<NameValuePair>();
reqParam.add(new NameValuePair("ticket", ticket));
webRequest.setRequestParameters(reqParam);

mypage = (HtmlPage) client.getPage(webRequest);

System.out.println(mypage.asXml());

}
}


相关标签: html unit