我正在尝试自动登录该网站:https://my.calpoly.edu.
网站的登录表单有一个密钥,该密钥在网站的每次请求时都会更改:
有什么办法绕过这个吗?我可以抓取所有输入元素并将它们存储到映射中,然后在第二个连接上发送POST请求,但我认为它不起作用,因为在第二次连接上,lt请求会更改。
这是我的代码:
Document doc = Jsoup.connect("https://my.calpoly.edu/").get();
Element loginForm = doc.getElementById("fm1");
Elements inputElements = loginForm.getElementsByTag("input");
HashMap<String, String> paramList = new HashMap<String, String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = URLEncoder.encode(inputElement.attr("value"), "UTF-8");
if (key.equals("username")) {
value = "user123";
}
else if (key.equals("password")) {
value = "pass123";
}
paramList.put(key, value);
}
//Iterator it = paramList.entrySet().iterator();
//while (it.hasNext()) {
// Map.Entry pairs = (Map.Entry)it.next();
// System.out.println(pairs.getKey() + "=" + pairs.getValue());
//}
Connection res = Jsoup.connect("https://my.calpoly.edu/cas/login");
res.data(paramList);
res.method(Method.POST);
res.userAgent("Mozilla");
Response response = res.execute();
System.out.println(response.body());
创建这样的文档:
Connection connect = Jsoup.connect("https://my.calpoly.edu/");
Document doc = connect.get();
然后,对于第二次连接,使用相同的对象,这样请求就不会改变:
Connection res = connect;
或者,您也可以直接使用connect
对象。