How to read cookie from org.eclipse.swt.browser.Browser?
I want to read JSESSIONID
from cookie org.eclipse.swt.browser.Browser
. I try to open browser from Eclipse plug-in. I am using below snippet
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();
}
But I am not getting cookie value.
Something like this : c# Get httponly cookie
Try getting the cookie from JavaScript instead of the Browser#getCookie()
method. It worked for me during my test, but as I don't know your website, I can't test it against it:
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();
}
If the cookie you wish to get is marked as httpOnly
then you won't be able to get it in current SWT versions. See this bug for a discussion.
上一篇: 事务回滚在被动应用程序中