我想从Cookie JSESSIONID
中读取org.eclipse.swt.browser.Browser
。我尝试从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值。
答案 0 :(得分:3)
尝试从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();
}
答案 1 :(得分:1)
如果您希望获得的Cookie标记为httpOnly
,那么您将无法在当前的SWT版本中获取它。有关讨论,请参阅this bug。