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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7728447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:10:21  来源:igfitidea点击:

how to maintain variable cookies and sessions with jsoup?

javasessioncookiesjsoup

提问by texasman1979

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;
}

This method is not right. What I'm trying to figure out is a way to without know what cookies will exist, be able to handle cookie changes as well as maintain sessions.

这个方法不对。我想弄清楚的是一种在不知道将存在哪些 cookie 的情况下,能够处理 cookie 更改以及维护会话的方法。

I'm writing an app for my simple machines forum, and it changes its cookie config as you click around for some custom behavior.

我正在为我的简单机器论坛编写一个应用程序,当您点击一些自定义行为时,它会更改其 cookie 配置。

But if the app does well for my site, I was going to publish a version for others to use for other forums.

但是,如果该应用程序对我的网站运行良好,我将发布一个版本供其他人用于其他论坛。

I know I'm heading in the right direction, but the logic is kind of kicking my butt.

我知道我正朝着正确的方向前进,但逻辑有点让我失望。

Any advice would be greatly appreciated.

任何建议将不胜感激。

回答by BalusC

This code is very confusing. The flow is illogical and the exception handling is bad. The object reference comparisons like if (p != path)and if (cookys != cookies)makes no utter sense. To compare object's contentsyou need to use equals()method instead.

这段代码非常混乱。流程不合逻辑,异常处理不好。对象引用比较像if (p != path)并且if (cookys != cookies)没有完全意义。要比较对象的内容,您需要改用equals()方法。

To the point, I understand that you want to maintain cookies in a bunch of subsequent Jsoup requests on the same domain. In that case, you need to basicallyadhere the following flow:

就这一点而言,我了解您希望在同一域上的一堆后续 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.

This can be refactored to the following method:

这可以重构为以下方法:

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();
}

which can be used as

可以用作

YourJsoupWrapper jsoupWrapper = new YourJsoupWrapper();

Document document1 = jsoupWrapper.get(url1);
// ...

Document document2 = jsoupWrapper.get(url2);
// ...

Document document3 = jsoupWrapper.get(url3);
// ...

Note that the upcoming Jsoup 1.6.2 will come with a new Connection#cookies(Map)method which should make that forloop everytime superfluous.

请注意,即将推出的 Jsoup 1.6.2 将带有一个新Connection#cookies(Map)方法,该方法应该使该for循环每次都是多余的。

回答by Bender

+1 for BalusC

BalusC +1

I changed some in your code and it works for me, so you get cookie from site and only than get Document

我在你的代码中更改了一些,它对我有用,所以你从站点获取 cookie 而只是获取文档

public Document get(String url) throws IOException {
    Connection connection = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
    Connection.Response response = connection.execute();
    connection.cookies(response.cookies());
    return connection.get();
}