javajerseyjersey-2.0jersey-client

Maintain cookie session with jersey CLIENT per client


I am using the client part of jersey API.

I am querying a rest endpoint that send me back a cookie like this one

Set-Cookie: SessionId=270080680;path=/myPath

Reading the doc and other Stack Overflow answers I am able to retrieve the cookie and send it back.

But can Jersey manage this cookie handling automatically per client? And send back what is needed to be sent back according to the path for example.

As suggested in comment the right way seems to create a filter and intercept request to store and reemit the cookie.

This solve one part of the problem, I still need to be clever and check the path of the endpoint to know which cookie I should send.

Can jersey do it for me?


Solution

  • Not applicable for everyone but in my case this solution fit perfectly ! So I decided to share it

    As suggested I started to create my own filter and everything seems ok! But sometimes I have seen that my cookie were duplicated.

    After digging this is what i found, so I am in the particular context of a JavaFX application and using the simplest jersey client implementation relying on HttpURLConnection.

    I notice that my cookie were duplicated from the time that my app display a WebView. I found this piece of code in WebPage.java

        if (CookieHandler.getDefault() == null) {
            boolean setDefault = Boolean.valueOf(System.getProperty(
                    "com.sun.webkit.setDefaultCookieHandler",
                    "true"));
            if (setDefault) {
                CookieHandler.setDefault(new CookieManager());
            }
        }
    

    So the bug was in fact my answer. Someone already take care of managing cookie in my case

    The one line managing all cookie jvm wide is :

    CookieHandler.setDefault(new CookieManager());
    

    I let you check the doc here and here to understand how to use it