如何使用jsoup维护可变cookie和会话?
问题内容:
public boolean isGood(String path)
{
if (p != path)
{
good = false;
}
if (good)
{
try
{
Connection connection = Jsoup.connect(path);
Map<String, String> cookys = Jsoup.connect(path).response().cookies();
if (cookys != cookies)
cookies = cookys;
for (Entry<String, String> cookie : cookies.entrySet())
{
connection.cookie(cookie.getKey(), cookie.getValue());
}
Doc = connection.get();
good = true;
}
catch (Exception e)
{
rstring = e.getMessage().toString();
good = false;
}
}
else
{
try
{
Response response = Jsoup.connect(path).execute();
cookies = response.cookies();
Doc = response.parse();
good = true;
}
catch (Exception e)
{
rstring = e.getMessage().toString();
good = false;
}
}
return good;
}
此方法不正确。我试图找出的是一种不知道将存在哪些cookie,能够处理cookie更改以及维护会话的方法。
我正在为我的简单机器论坛编写一个应用程序,当您单击某些自定义行为时,它会更改其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
循环在每一次都是多余的。