Java – sends a post request using a user name and password and saves a session cookie

After sending a post request with a user name and password, how do I save cookies using jsup? Or do I have to provide it to the connection object first and then save it?

Solution

Suppose the HTML form is as follows:

<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 and get cookies as follows:

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 return cookies according to the following requirements:

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

Or if you know the personal cookie Name:

Document document = Jsoup.connect("http://example.com/user")
    .cookie("SESSIONID",cookies.get("SESSIONID"))
    .get();
// ...
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>