java jsoup获取cookie_java – 如何使用jsoup维护变量cookie和会话?
這段代碼非常令人困惑.流程不合邏輯,異常處理很糟糕.像if(p!= path)和if(cookys!= cookies)之類(lèi)的對(duì)象引用比較沒(méi)有任何意義.要比較對(duì)象的內(nèi)容,您需要使用equals()方法.
到目前為止,我知道您希望在同一個(gè)域上的一堆后續(xù)Jsoup請(qǐng)求中維護(hù)cookie.在這種情況下,您需要基本遵循以下流程:
Map cookies = new HashMap();
// First request.
Connection connection1 = Jsoup.connect(url1);
for (Entry 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 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 cookie : cookies.entrySet()) {
connection3.cookie(cookie.getKey(), cookie.getValue());
}
Response response3 = connection3.execute();
cookies.putAll(response3.cookies());
Document document3 = response3.parse();
// ...
// Etc.
這可以重構(gòu)為以下方法:
private Map cookies = new HashMap();
public Document get(url) throws IOException {
Connection connection = Jsoup.connect(url);
for (Entry 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);
// ...
請(qǐng)注意,即將推出的Jsoup 1.6.2將附帶一個(gè)新的Connection#cookies(Map)方法,該方法應(yīng)該使循環(huán)每次都是多余的.
總結(jié)
以上是生活随笔為你收集整理的java jsoup获取cookie_java – 如何使用jsoup维护变量cookie和会话?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 怎么看表_干货 | 剪力墙、柱、板配筋率
- 下一篇: 知识图谱入门视频(二)