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?
Asked
Active
Viewed 1.1k times
9

BalusC
- 1,082,665
- 372
- 3,610
- 3,555

Jevgeni Smirnov
- 3,787
- 5
- 33
- 50
-
See also: http://stackoverflow.com/a/10533366/363573 – Stephan Jul 11 '15 at 08:53
1 Answers
14
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();
// ...

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
3Good point on the .cookies(map) suggestion. There's one there for .data(). I'll look to add it soon. – Jonathan Hedley Aug 27 '11 at 01:37
-
3OK I've that method; available now if you build from head, or in 1.6.2 soon. https://github.com/jhy/jsoup/commit/93ff111c590ea57b311705360111a3e54329a026 – Jonathan Hedley Aug 28 '11 at 06:15