如何从org.eclipse.swt.browser.Browser读取cookie?

我想从cookie org.eclipse.swt.browser.Browser读取JSESSIONID 。 我尝试从Eclipse插件打开浏览器。 我正在使用下面的代码片段

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

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

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

    final String url = "https://....";
    browser.setUrl(url);
    browser.addProgressListener(new ProgressAdapter() {
        @Override
        public void completed(ProgressEvent event) {
            String cookieText = "cookie=" + Browser.getCookie("JSESSIONID", url);
            System.out.println(cookieText);
        }
    });
    shell.setSize(400, 300);
    shell.open();

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

    display.dispose();
}

但我没有获得cookie的价值。

就像这样:c#获取httponly cookie


尝试从JavaScript代替Browser#getCookie()方法获取cookie。 它在我的测试过程中为我工作,但由于我不知道你的网站,我无法对它进行测试:

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

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

    final Browser browser = new Browser(shell, SWT.NONE);
    browser.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    final String url = "https://...";
    browser.setUrl(url);

    /* Define the function to call from JavaScript */
    new BrowserFunction(browser, "cookieCallback") {
        @Override
        public Object function(Object[] objects) {

            Object[] keyValuePairs = (Object[]) objects[0];

            for(Object keyValue : keyValuePairs)
            {
                Object[] pair = (Object[]) keyValue;

                if(Objects.equals("JSESSIONID", pair[0]))
                    System.out.println(pair[1]);
            }

            return null;
        }
    };

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Get cookie");
    button.addListener(SWT.Selection, new Listener() {
        @Override
        public void handleEvent(Event event) {
            /* Get the cookie from JavaScript and then call the function */
            browser.execute("cookieCallback(document.cookie.split( ';' ).map( function( x ) { return x.trim().split( '=' ); } ));");
        }
    });

    shell.setSize(400, 300);
    shell.open();

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

    display.dispose();
}

如果您希望获取的cookie标记为httpOnly那么您将无法在当前的SWT版本中获取它。 查看此错误进行讨论。

链接地址: http://www.djcxy.com/p/32781.html

上一篇: How to read cookie from org.eclipse.swt.browser.Browser?

下一篇: Loop exits with Task was destroyed but it is pending