Search code examples
javasessionjettyokhttpspark-java

OkHttp new session


I have an http server, and it uses sessions, but every time I send a request from okhttp the server creates a new session.

The server uses jetty with sparkjava. In a browser it works normally, and the console confirms that. With okhttp it is not working properly, and the console confirms my suspicion about sessions. How can I fix that?

I can`t write a minimal reproducible example, because I have not small project (<2500 lines) and I think it isn't useful.

How do I get okhttp to send requests with only one session?


Solution

  • It is not the OkHttp client's job to manage request and response cookies. It cannot know the cookie policy and which requests belongs to a certain "session". However, it provides a client related CookieJar interface that can be used to save and load Cookie instances per request URL.

    Like so:

        var acceptingCookieJar = new CookieJar() {
            ConcurrentHashMap<URI, List<Cookie>> cookieMap = new ConcurrentHashMap<>();
    
            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                return cookieMap.computeIfAbsent(url.uri(), k -> Collections.emptyList());
            }
    
            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                cookieMap.put(url.uri(), cookies);
            }
        };
    
    
        var client = new OkHttpClient.Builder()
                .cookieJar(acceptingCookieJar)
                .build();
    

    Note that this is just an example. Depending on your use case, it might be enough to just store the host part of the request URL, or it might be necessary to keep track of several session ids, for example JSESSIONID.