无法使用带有 x-www-form-urlencoded 参数的 JSOUP 登录网站

Ana*_*oly 2 java jsoup

如何使用Jsoup实现以下请求?

POST /login/user HTTP/1.1
主机:url.publishedprices.co.il
缓存控制:无缓存内容类型:application/x-www-form-urlencoded

用户名=只读&密码=123456&csrftoken=wohewqfDrcK2JMK5w7BKw4jCuMOiARnDg01Rw4VZdQ%3D%3D

我已尝试以下代码,但它不起作用,我从网站收到错误

未收到预期的安全令牌

我正在使用这段代码:

Document welcomePage = Jsoup.connect("https://url.publishedprices.co.il/login").get();
Element inputHidden = welcomePage.getElementById("csrftoken");


String securityTokenKey = inputHidden.attr("name");
String securityTokenValue = inputHidden.attr("value");

Connection.Response res2 = Jsoup.connect("https://url.publishedprices.co.il/login/user")
        .header("Content-Type","application/x-www-form-urlencoded;charset=UTF-8")
        .data("username", "readonly")
        .data("password", "123456")
        .data(securityTokenKey, securityTokenValue)
        .method(Method.POST)
        .execute();

System.out.println(res2.body());
Map<String, String> loginCookies = res2.cookies();
Run Code Online (Sandbox Code Playgroud)

我知道当我使用时x-www-form-urlencoded我需要在 URL 中对其进行编码,但假设当我设置正确的标头 JSOUP 时为我做这件事,我错了吗?

谢谢。

Rom*_*man 5

您应该传递 cookie(其中包含带有秘密令牌的会话),以便服务器端的 CSRF 保护能够比较令牌并授予您访问权限。


Connection.Response res1 = Jsoup.connect("https://url.publishedprices.co.il/login").method(Method.GET).execute();
        Document welcomePage = res1.parse();
        Map welcomCookies = res1.cookies();
        Element inputHidden = welcomePage.getElementById("csrftoken");


        String securityTokenKey = inputHidden.attr("name");
        String securityTokenValue = inputHidden.attr("value");

        Connection.Response res2 = Jsoup.connect("https://url.publishedprices.co.il/login/user")
                .header("Content-Type","application/x-www-form-urlencoded;charset=UTF-8")
                .data("username", "readonly")
                .data("password", "123456")
                .data(securityTokenKey, securityTokenValue)
                .cookies(welcomCookies)
                .method(Method.POST)
                .execute();

        System.out.println(res2.body());