Search code examples
javajsoup

Jsoup POST request failure. HTTP error fetching URL. Status=400


I'm trying to log in a website(https://dashboard.ngrok.com/user/login) using jsoup. I hadn't any problem with GET request, but when I try to do a POST request using credential I recive:

HTTP error fetching URL. Status=400

I tried to set a better header for the request, using the same parameters that I send when I connect making a POST request.

Connection.Response loginForm = Jsoup.connect(url)
           .method(Connection.Method.GET).execute();
System.out.println("GET");

Document document = Jsoup.connect(url)
           .data("email", usr)
           .data("password", psw)
           .header("Host", "dashboard.ngrok.com")
           .header("Origin", "https://dashboard.ngrok.com")
           .referrer(url)
           .cookies(loginForm.cookies())
           .post();

I also tried this type of request:

Response res = Jsoup.connect(url)
            .data("email", usr, "password", psw)
            .method(Method.POST)
            .execute();
Map<String, String> loginCookies = res.cookies();

Document doc = Jsoup.connect(ngrok)
    .cookies(loginCookies)
    .get();

The Output says:

Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=400, URL=https://dashboard.ngrok.com/user/login


Solution

  • As TDG advised me I added the csrf_token. The result code is this:

    CookieHandler.setDefault(new CookieManager());
    
        Connection.Response loginForm = Jsoup.connect(url)
                .method(Connection.Method.GET)
                .userAgent(USER_AGENT).execute();
    
        Document tok = loginForm.parse();
        Element e = tok.select("input[name=csrf_token]").first();
        String appToken = e.attr("value");
        System.out.println(appToken);
        Connection.Response login = Jsoup.connect(url)
                    .data("email", usr)
                    .data("password", psw)
                    .data("csrf_token", appToken)
                    .userAgent(USER_AGENT)
                    .header("Host", "dashboard.ngrok.com")
                    .header("Origin", "https://dashboard.ngrok.com")
                    .referrer(url)
                    .cookies(loginForm.cookies())
                    .method(Method.POST)
                    .execute();
    

    Thank you for the help.