Hiphop03199
Hiphop03199

Reputation: 720

Destroying Cookies from SWT's Browser

I've been having trouble with the SWT Browser class's management of cookies. The cookies created by the browser appear to persist between sessions, but are difficult to track down and delete.

In particular, I'd like to remove a specific cookie that is created during an authentication process for Stack Exchange.

Right now, I'm able to print out the existing cookie data, but can't figure out how to edit or (ideally) remove the cookie using the Browser.setCookie method.

Here's my code at the moment:

// 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] 

Because there is no clear methods to view cookies stored by the SWT browser, or to clear all cookies stored, I'm a bit stuck as to how to reset these values. I've tried a few variations of the setCookie() arguments with no success so far.

Thank you in advance for any suggestions or help.

Upvotes: 0

Views: 713

Answers (1)

Baz
Baz

Reputation: 36904

The JavaDoc of Browser#setCookie() is quite clear:

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)

The code below creates a cookie, then prints it, deletes it and prints again.

Output:

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

Upvotes: 1

Related Questions