栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用jsoup维护可变cookie和会话?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用jsoup维护可变cookie和会话?

这段代码很混乱。流是不合逻辑的,并且异常处理不好。对象引用比较喜欢

if (p != path)
if (cookys !=cookies)
不作任何绝对的意义。要比较对象的 内容, 您需要改用
equals()
method。

到目前为止,我了解到您想在同一域中的一系列后续Jsoup请求中维护cookie。在这种情况下,您需要 基本上 遵循以下流程:

Map<String, String> cookies = new HashMap<String, String>();// First request.Connection connection1 = Jsoup.connect(url1);for (Entry<String, String> cookie : cookies.entrySet()) {    connection1.cookie(cookie.getKey(), cookie.getValue());}Response response1 = connection1.execute();cookies.putAll(response1.cookies());document document1 = response1.parse();// ...// Second request.Connection connection2 = Jsoup.connect(url2);for (Entry<String, String> cookie : cookies.entrySet()) {    connection2.cookie(cookie.getKey(), cookie.getValue());}Response response2 = connection2.execute();cookies.putAll(response2.cookies());document document2 = response2.parse();// ...// Third request.Connection connection3 = Jsoup.connect(url3);for (Entry<String, String> cookie : cookies.entrySet()) {    connection3.cookie(cookie.getKey(), cookie.getValue());}Response response3 = connection3.execute();cookies.putAll(response3.cookies());document document3 = response3.parse();// ...// Etc.

可以将其重构为以下方法:

private Map<String, String> cookies = new HashMap<String, String>();public document get(url) throws IOException {    Connection connection = Jsoup.connect(url);    for (Entry<String, String> cookie : cookies.entrySet()) {        connection.cookie(cookie.getKey(), cookie.getValue());    }    Response response = connection.execute();    cookies.putAll(response.cookies());    return response.parse();}

可以用作

YourJsoupWrapper jsoupWrapper = new YourJsoupWrapper();document document1 = jsoupWrapper.get(url1);// ...document document2 = jsoupWrapper.get(url2);// ...document document3 = jsoupWrapper.get(url3);// ...

请注意,即将到来的Jsoup 1.6.2将带有一个新

Connection#cookies(Map)
方法,该方法应使该
for
循环在每一次都是多余的。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/419304.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号