开发者

Sending POST request with username and password and save session cookie

开发者 https://www.devze.com 2023-03-31 04:51 出处:网络
How can I save cookies with Jsoup after sending a POST request with username and password? Or must I first provid开发者_如何学Ce them to connection object and then save?Assuming that the HTML form loo

How can I save cookies with Jsoup after sending a POST request with username and password? Or must I first provid开发者_如何学Ce them to connection object and then save?


Assuming that the HTML form look like below:

<form action="http://example.com/login" method="post">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="submit" name="login" value="Login" />
</form>

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<String, String> 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

精彩评论

暂无评论...
验证码 换一张
取 消