Guilherme Lima Pereira Guilherme Lima Pereira - 1 month ago 12
Java Question

JSOUP - JSP Login: Blank cookie

I've seen some answers about this, here in the Stackoverflow but none of them solved my problem...

I want to perform a login in a JSP page, using Jsoup. Below you can see my code. The problem is that the second request using post doesn't return any Cookie, so, my last request can't reach the page that is after the login.

I'm sure the data is correct ("acao", "num" and "senha")... I inspected the request after a login in chrome (developer tools > network tab > seen the form data content).

Any ideas of what can be happenning with the code?

public class Extrator {

public static void main(String[] args) throws IOException {
@SuppressWarnings("unused")
Connection.Response loginForm = Jsoup.connect("URL LOGIN JSP")
.method(Connection.Method.GET)
.execute();

@SuppressWarnings("unused")
Connection.Response login = Jsoup.connect("URL LOGIN JSP")
.data("acao", "entrar")
.data("num", "user")
.data("senha", "password")
.cookies(loginForm.cookies())
.method(Method.POST)
.execute();

Map<String, String> cookies = login.cookies();

Document page = Jsoup.connect("PAGE AFTER LOGIN")
.cookies(cookies)
.get();
}
}

Answer

Problem

The response from your form submission (login) doesn't contain the cookie with the JSESSIONID, so for the last request, you are not sending any cookies to the page.

Solution

Use the cookies with the JSESSIONID from loginForm:

try {
    Response loginForm = Jsoup.connect("http://sac.desktop.com.br/Cliente_Login.jsp")
        .method(Method.GET)
        .execute();

    Response login = Jsoup.connect("http://sac.desktop.com.br/Cliente_Menu.jsp")
        .data("acao", "entrar")
        .data("num", "user")
        .data("senha", "password")
        .cookies(loginForm.cookies())
        .method(Method.POST)
        .execute();

    Document page = Jsoup.connect("http://sac.desktop.com.br/Cliente_Menu.jsp")
        .cookies(loginForm.cookies())
        .get();

    System.out.println(page.html());
} catch (IOException e) {
    e.printStackTrace();
}
Comments