JavaFX WebView cookie

时间:2013-07-08 10:32:02

标签: webview javafx

如何通过JavaFX WebView与网页的连接获取cookie。我想使用此cookie,以便在originaol登录后打开与网站的单独连接。 有没有办法做到这一点以及如何做?

感谢您的时间

1 个答案:

答案 0 :(得分:2)

我有一个本地“login.html”,它对我的​​服务器进行AJAX调用以登录。

JavaFX应用程序代码:

public class Main extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Battleround client");

        URL loginPageUrl = Main.class.getResource("/pages/login.html");

        final WebView webview = new WebView();
        final WebEngine webEngine = webview.getEngine();

        webEngine.setJavaScriptEnabled(true);
        webEngine.load(loginPageUrl.toString());

        /*
         * Alright, this piece of code might be hard to understand. Basically
         * we're adding a JavaScript object that's actually a Java object. So we
         * can call Java methods from JavaScript. And we're adding this
         * javascript object as soon as the page has been fully loaded.
         */
        webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
            @Override
            public void changed(ObservableValue<? extends State> ov, State t, State t1) {
                if (t1 == Worker.State.SUCCEEDED) {
                    JSObject window = (JSObject) webEngine.executeScript("window");
                    window.setMember("java", new AuthenticationApplication());
                }
            }
    });

    StackPane root = new StackPane();
    root.getChildren().add(webview);
    primaryStage.setScene(new Scene(root, 400, 500));
    primaryStage.show();
}

public class AuthenticationApplication {
    public void start(String JSESSIONID) {
        // From here on I start my game with the JSESSIONID from the login call.
    }
}

我在login.html中的JavaScript代码:

function login(username, password) {
    var xmlHttp = new XMLHttpRequest();
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    var url = "http://192.168.2.7:8888/Login";
    var params = "username=" + userName + "&password=" + password;
    xmlHttp.open("POST", url, true);

    // Send the proper header information along with the request
    xmlHttp.setRequestHeader("Content-type",
        "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.withCredentials = "true";
    xmlHttp.onreadystatechange = function() {// Call a function when the state changes.
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            if(xmlHttp.responseText == "login.successful") {
                document.getElementById("loginForm").innerHTML = getResources("login.successful");
                var setCookieHeader = xmlHttp.getResponseHeader('Set-Cookie');
                java.start(setCookieHeader.split(";")[0].split("=")[1]); // Obtain the JSESSIONID, and send it to the java code. Warning: this code will mess up if there's other cookies.
            } else {
                document.getElementById("validationMessage").innerHTML = getResources(xmlHttp.responseText);
            }
        }
    };
    xmlHttp.send(params);
}

function getResources(key) {
    var resources = {};

    resources["login.already.logged.in"] = "You are already logged in! Log out first if you want to try again.";
    resources["login.error"] = "The login failed because an error occurred, Sorry!";
    resources["login.failed"] = "User name and password do not match.";
    resources["login.successful"] = "Login succeeded.";

    return resources[key];
}