tex*_*979 5 java cookies session jsoup
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;
}
Run Code Online (Sandbox Code Playgroud)
这种方法不对.我想弄清楚的是一种不知道cookie将存在的方法,能够处理cookie更改以及维护会话.
我正在为我的简单机器论坛编写一个应用程序,当你点击一些自定义行为时它会改变它的cookie配置.
但是,如果该应用程序对我的网站运行良好,我将发布一个版本供其他人用于其他论坛.
我知道我正在朝着正确的方向前进,但逻辑却有点踢我的屁股.
任何建议将不胜感激.
Bal*_*usC 14
这段代码非常令人困惑.流程不合逻辑,异常处理也很糟糕.对象引用比较喜欢if (p != path)并且if (cookys != cookies)没有任何意义.要比较对象的内容,您需要使用equals()方法.
到目前为止,我知道您希望在同一个域上的一堆后续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.
Run Code Online (Sandbox Code Playgroud)
这可以重构为以下方法:
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();
}
Run Code Online (Sandbox Code Playgroud)
可以用作
YourJsoupWrapper jsoupWrapper = new YourJsoupWrapper();
Document document1 = jsoupWrapper.get(url1);
// ...
Document document2 = jsoupWrapper.get(url2);
// ...
Document document3 = jsoupWrapper.get(url3);
// ...
Run Code Online (Sandbox Code Playgroud)
请注意,即将推出的Jsoup 1.6.2将附带一个新Connection#cookies(Map)方法,该方法应该使for循环每次都是多余的.
| 归档时间: |
|
| 查看次数: |
14168 次 |
| 最近记录: |