Javafx WebView不能保存cookie

 2023-02-17    472  

问题描述

我是Javafx的新手,需要使用浏览器窗口编程应用程序.浏览器将用于登录Microstock代理Fotolia,以求解登录处的验证码.显然,关闭并以后重新启动我的应用程序时,cookie不会保存.

有没有办法在Javafx/WebView中存储下一个会话的cookie?还是可以告诉我,为什么饼干没有存储?

Javafx WebView不能保存cookie

推荐答案

Javafx WebView使用内存cookie商店,因此不会在会话之间持续cookie.
您需要自己实施cookie商店.

public class myCookieStore implements CookieStore {...this is where you implement the interface...}

然后,在该商店内部,您可以维护cookie的列表.
可能是这样的,但取决于您.

private List<HttpCookie> cookies = new ArrayList<>();

这样做后,在Javafx初始化函数中,您将WebEngine Cookiestore设置为实现.

@Override
public void initialize(URL location, ResourceBundle resources) {
    WebEngine engine = this.webViewID.getEngine();
    java.net.CookieManager manager = new CookieManager(new myCookieStore(),CookiePolicy.ACCEPT_ALL);
    java.net.CookieHandler.setDefault(manager);}

在您实现库克iestore的内部,您必须将该cookie的列表保存到文件(或数据库,或任何放置的地方)时,每当它更改时,然后在应用程序重新加载时重新加载.

这是我个人遇到障碍以及如何找到您的问题的地方. httpcookie无法实现序列化,并且具有不会反映的私有字段 – 这意味着您不能简单地序列化和划分列表并使用gson.tojson()(此处列出的解决方案使用Javafx的WebEngine/webview 设置cookie也会失败.您可能必须手动保存Cookie字段,然后重建Cookie.如果我实际上让它自己工作,我会用解决方案来更新此问题.

///update////////
事实证明,HTTPCookie的串行问题以Java 9开头.如果您使用Java 8,则可以简单地实现Cookiestore接口,然后在先前链接的帖子中使用GSON示例来坚持该列表.但是,如果您使用的是Java 9或更高版本,那么您将无法再这样做,因为它会阻止GSON用于访问私有字段的反射.

我重新完成了HTTPCookie对象的公开访问成员,例如:

public class myCookieClass implements Serializable{
    private URI uri;
    private String name;
    private String value;
    private String domain;
    private String path;
    private String portList;
    private String comment;
    private String commentURL;
    private boolean httpOnly;
    private boolean discard;
    private long maxAge;
    private boolean secure;
    private int version;



    public myCookieClass(URI uri, HttpCookie cookie){
        name = cookie.getName();
        value = cookie.getValue();
        domain = cookie.getDomain();
        maxAge =cookie.getMaxAge();
        path = cookie.getPath();
        httpOnly = cookie.isHttpOnly();
        portList = cookie.getPortlist();
        discard = cookie.getDiscard();
        secure = cookie.getSecure();
        version = cookie.getVersion();
        comment = cookie.getComment();
        commentURL = cookie.getCommentURL();
        this.uri = uri;
    }

    public HttpCookie toCookie(){
        HttpCookie cookie =  new HttpCookie(this.name,this.value);
        cookie.setSecure(secure);
        cookie.setDomain(domain);
        cookie.setMaxAge(maxAge);
        cookie.setPath(path);
        cookie.setHttpOnly(httpOnly);
        cookie.setPortlist(portList);
        cookie.setDiscard(discard);
        cookie.setVersion(version);
        cookie.setComment(comment);
        cookie.setCommentURL(commentURL);
        cookie.setValue(value);
        return cookie;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        myCookieClass that = (myCookieClass) o;
        return  uri.equals(that.uri) &&
                name.equals(that.name);

    }

    @Override
    public int hashCode() {
        return Objects.hash(uri, name);
    }
}

然后,我正在使用与以前相同的GSON示例来保存和还原该列表.

public void RestoreCookieStoreFromFile(){
    try {
        File file = new File(fileName);
        if (file.exists()) {
            System.out.println("RESTORE COOKIES");
            FileReader fileReader = new FileReader(fileName);
            String json = new String(Files.readAllBytes(Paths.get(fileName)));
            Gson gson = new GsonBuilder().create();
            Type type = new TypeToken<List<myCookieClass>>() {
            }.getType();
            cookies = gson.fromJson(json, type);

        }
        } catch(FileNotFoundException e){
            //file not found
            e.printStackTrace();
        } catch(IOException e){
            // cant create object stream
            e.printStackTrace();
        }


}

private void saveCookieStoreToFile(String location){
    try {
        Gson gson = new GsonBuilder().create();
        String jsonCookie = gson.toJson(cookies);
        Files.writeString(Path.of(fileName),jsonCookie);

    } catch (FileNotFoundException e) {
        // file not found
        System.out.println("Can't Save File");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("Can't Save File OUTSTREAM");
        // can't create output stream
        e.printStackTrace();
    }
    catch (InaccessibleObjectException e){
        System.out.println("Can't Access object");
        e.printStackTrace();
    }
}

至少在我的情况下,这些是实际从事这项工作的Cookiestore接口成员.还有更多成员,但似乎没有什么称呼这些成员.

@Override
public void add(URI uri, HttpCookie cookie)
{

        cookies.add(new myCookieClass(uri,cookie));

        saveCookieStoreToFile(fileName);

}


@Override
public List<HttpCookie> get(URI uri) {


    List<HttpCookie> uriCookies = new ArrayList<>();
    myCookieClass[] tempCookies = cookies.toArray(myCookieClass[]::new);
    for (myCookieClass c: tempCookies) {
        if(c.uri.toString().contains(uri.getRawAuthority())){
            uriCookies.add(c.toCookie());
        }
    }
        return uriCookies;
}


@Override
public List<HttpCookie> getCookies() {

        List<HttpCookie> httpCookies = new ArrayList<>();
        myCookieClass[] tempCookies = cookies.toArray(myCookieClass[]::new);
        for (myCookieClass c : tempCookies) {
            httpCookies.add(c.toCookie());
        }

        return httpCookies;

}

仅出于完整性,这是将我的cookie保存在内存中的列表.

private List<myCookieClass> cookies = new ArrayList<>();

一如既往,祝你好运!

以上所述是小编给大家介绍的Javafx WebView不能保存cookie,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!

原文链接:https://77isp.com/post/34142.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。