Sending POST request with username and password and save session cookie

后端 未结 1 418
再見小時候
再見小時候 2020-11-29 09:50

How can I save cookies with Jsoup after sending a POST request with username and password? Or must I first provide them to connection object and then save?

1条回答
  •  自闭症患者
    2020-11-29 10:28

    Assuming that the HTML form look like below:

    You can POST it and obtain cookies as below:

    Response response = Jsoup.connect("http://example.com/login")
        .method(Method.POST)
        .data("username", username)
        .data("password", password)
        .data("login", "Login")
        .execute();
    Map cookies = response.cookies();
    Document document = response.parse(); // If necessary.
    // ...
    

    You can pass cookies back on subsequent requests as below:

    Document document = Jsoup.connect("http://example.com/user")
        .cookies(cookies)
        .get();
    // ...
    

    Or if you know the individual cookie name:

    Document document = Jsoup.connect("http://example.com/user")
        .cookie("SESSIONID", cookies.get("SESSIONID"))
        .get();
    // ...
    

    0 讨论(0)
提交回复
热议问题