如何使用Jsoup登录页面

时间:2013-09-13 05:35:00

标签: java jsoup

经过几个小时的搜索后,我仍然对登录后如何访问html页面感到有点难过。看看这里的各种其他帖子以及Jsoup API,我明白访问登录页面后的页面将需要一些这样的代码:

    Connection.Response loginForm = Jsoup.connect("https://parentviewer.pisd.edu/")
            .method(Connection.Method.GET)
            .execute();

    Document document = Jsoup.connect("https://parentviewer.pisd.edu/")
            .data("username", "testUser")
            .data("password", "testPass")
            .data("LoginButton", "Login")
            .cookies(loginForm.cookies())
            .post();

然而,我认为我的理解可能有些偏差,因为我仍然不完全准确地说明我应该为每个值添加什么。

例如,在网站上,我会使用输入名称=“ctl00 $ ContentPlaceHolder1 $ portalLogin $ UserName”作为键,“testUser”作为值吗?

我接近这项任务的方法是否正确? 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:6)

是的,此代码看起来与您的相同。

Connection.Response loginForm = Jsoup.connect("https://parentviewer.pisd.edu/")
        .method(Connection.Method.GET)
        .execute();

Document document = Jsoup.connect("https://parentviewer.pisd.edu/")
        .data("ctl00$ContentPlaceHolder1$portalLogin$UserName", "testUser")
        .data("ctl00$ContentPlaceHolder1$portalLogin$Password", "testPass")
        .cookies(loginForm.cookies())
        .post();

System.out.println(document.body().html());

如何使这个工作?最好的方法是在浏览器中启用Web Developer Console并登录此页面。在此之后检查从broswer发送到服务器的内容并使用JSoup发送此数据。

在您的示例请求中,数据如下所示:

Request URL:https://parentviewer.pisd.edu/
Request Method:POST
Status Code:200 OK

FormData:
__LASTFOCUS:
__EVENTTARGET:
__EVENTARGUMENT:
__VIEWSTATE:/wEPDwULLTEwNjY5NzA4NTBkZMM/uYdqyffE27bFnREF10B/RqD4
__SCROLLPOSITIONX:0
__SCROLLPOSITIONY:106
__EVENTVALIDATION:/wEdAASCW34hepkNwIXSnvGxEUTlqcZt0XO7QUOibAd3ocrpayqHxD2e5zCnWBj9+m7TCi0S+C76MEjhL0ie/PsBbOp+Shjkt2W533uAqvBQcWZNXoh672M=
ctl00$ContentPlaceHolder1$portalLogin$UserName:testUser@gmail.com
ctl00$ContentPlaceHolder1$portalLogin$Password:testPass
ctl00$ContentPlaceHolder1$portalLogin$LoginButton:Login

并非所有数据都是必需的,请尝试使用最少的请求并检查是否有效。