使用用户名和密码发送POST请求并保存会话Cookie [英] Sending POST request with username and password and save session cookie

查看:1442
本文介绍了使用用户名和密码发送POST请求并保存会话Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在使用用户名和密码发送POST请求后使用Jsoup保存Cookie?或者我必须首先提供它们到连接对象然后保存?

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?

推荐答案

假设HTML表单如下所示:

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>

您可以POST并获取以下Cookie:

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.
// ...

您可以在后续请求中传递Cookie,如下所示: / p>

You can pass cookies back on subsequent requests as below:

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

或者如果您知道单个Cookie名称:

Or if you know the individual cookie name:

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

这篇关于使用用户名和密码发送POST请求并保存会话Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆