gpt4 book ai didi

java - 从 SWT 浏览器销毁 Cookie

转载 作者:行者123 更新时间:2023-12-01 10:07:09 26 4
gpt4 key购买 nike

我在 SWT Browser 类的 cookie 管理方面遇到了问题。浏览器创建的 cookie 似乎会在 session 之间持续存在,但很难追踪和删除。

特别是,我想删除在 Stack Exchange 身份验证过程中创建的特定 cookie。

现在,我可以打印出现有的 Cookie 数据,但无法弄清楚如何使用 Browser.setCookie 方法编辑或(理想情况下)删除 Cookie。

这是我目前的代码:

// Check the 'acct' cookie
System.out.println("Check Cookie: " + Browser.getCookie("acct", "http://www.stackexchange.com"));
// Outputs "Check Cookie: t=X123X&s=X123X" [redacted id's]

// Try to reset the cookie
Browser.setCookie("acct=; expires=Thu, 01-Jan-1970 00:00:01 GMT", "http://www.stackexchange.com");

// Read the cookie back again
System.out.println("Updated Cookie: " + Browser.getCookie("acct", "http://www.stackexchange.com"));
// Outputs "Updated Cookie: t=X123X&s=X123X" [same data as before]

因为没有明确的方法来查看 SWT 浏览器存储的 cookie,或清除存储的所有 cookie,所以我对如何重置这些值有点困惑。我已经尝试了 setCookie() 参数的一些变体,但到目前为止没有成功。

预先感谢您的任何建议或帮助。

最佳答案

JavaDoc of Browser#setCookie()非常清楚:

Sets a cookie on a URL. Note that cookies are shared amongst all Browser instances. The value parameter must be a cookie header string that complies with RFC 2109. The value is passed through to the native browser unchanged.

Example value strings: foo=bar (basic session cookie) foo=bar; path=/; domain=.eclipse.org (session cookie) foo=bar; expires=Thu, 01-Jan-2030 00:00:01 GMT (persistent cookie) foo=; expires=Thu, 01-Jan-1970 00:00:01 GMT (deletes cookie foo)

下面的代码创建一个 cookie,然后打印它,删除它并再次打印。

输出:

Cookie foo: bar

Cookie foo: null

public static void main(String[] args)
{
Display display = new Display();

Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());

Browser browser = new Browser(shell, SWT.NONE);

String url = "http://localhost:8080/";

/* Set the cookie */
Browser.setCookie("foo=bar", url);

System.out.println("Cookie foo: " + Browser.getCookie("foo", url));

/* Delete the cookie by setting to expired date */
Browser.setCookie("foo=; expires=Thu, 01-Jan-1970 00:00:01 GMT", url);

System.out.println("Cookie foo: " + Browser.getCookie("foo", url));

shell.pack();
shell.open();

while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}

display.dispose();
}

关于java - 从 SWT 浏览器销毁 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36367948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com