Exception in thread “main“ org.jsoup.HttpStatusException: HTTP error fetching URL. Status=422, URL=

x33g5p2x  于2021-12-28 转载在 其他  
字(1.9k)|赞(0)|评价(0)|浏览(428)

在使用JSoup模拟登录我校内网的时候报了如下错误:

Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=422, URL=https://webvpn.ncepu.edu.cn/users/sign_in
	at jsoup@1.10.2/org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:679)
	at jsoup@1.10.2/org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:628)
	at jsoup@1.10.2/org.jsoup.helper.HttpConnection.execute(HttpConnection.java:260)
	at EDM.login_final.main(login_final.java:66)

错误原因:模拟登录需要提交表单数据(浏览器按F12可查看):

utf8: ✓
authenticity_token: DNLRC2amJXtJtAypVp+4O9igPVAd+743zAK9AJbkTXWiojT0612nc5bDJjQjdX0au/YWR7xnbOwtULk4O5ACpg==
user[login]: ************
user[password]: ******
user[dymatice_code]: unknown
commit: 登录 Login

刚开始我是直接手动给connect对象添加数据,总是报422错误。调试了一段时间后发现:表单数据中的authenticity_token竟然是动态变化的…。于是这种做法就是错误的:

connect.data("user[login]", "************").data("user[password]", "******");
connect.data("dymatice_code", "unknown").data("utf8", "?").data("commit", "登录 Login");
connect.data("authenticity_token", "dbZNX3RljHFODgsb3tqZszd/jHjOrQYvnfhwWrPzTCU39NfVO9UcG5/rT3aKgxYu7xfCudoq4ibcDfn0rCZG0A==");

解决办法:动态请求网页数据来获得form data:

Connection con = Jsoup.connect(LOGIN_URL); 
con.header(USER_AGENT, USER_AGENT_VALUE); 
Response res = con.execute();
Document d = Jsoup.parse(res.body());       // 通过Jsoup将返回信息转换为Dom树
List<Element> elements = d.select("form");  // 获取提交form表单,可以通过查看页面源码代码得知
Map<String, String> datas = new HashMap<>();
for (Element e : elements.get(0).getAllElements()) {
    if (e.attr("name").equals("user[login]")) {
        e.attr("value", ************);
    }
    if (e.attr("name").equals("user[password]")) {
        e.attr("value", ******);
    }
     //添加其它信息
    if (e.attr("name").length() > 0) {
        datas.put(e.attr("name"), e.attr("value"));
    }
}

相关文章