2

I'm testing out some usages on CookieManager and I noticed that when I pass my deserialized cookie to CookieHandler, the format that CookieHandler uses to put it in cookie manager is not the same that I passed.

Sample code:

import org.springframework.http.HttpHeaders;

import java.io.IOException;
import java.net.*;
import java.util.*;

public class MainTest {

    public static void main(String[] args) throws URISyntaxException, IOException {

        HttpHeaders headers = new HttpHeaders();

        headers.add("Set-Cookie", "TEST=%7B%22keyType%22%3A%22abc%22%2C%22keyValue%22%3A%221.0%22%7D;Max-Age=600;Path=/;Version=0;SameSite=None");
        headers.add(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.9");

        System.out.println("headers-> " + headers);

        String uri = "http://test.com/test";
        CookieManager cookieHandler = new CookieManager();
        CookieHandler.setDefault(cookieHandler);

        URI uri1 = new URI(uri);
        CookieHandler.getDefault().put(uri1,headers);

        Map<String, List<String>> cookies = CookieHandler.getDefault().get(uri1,headers);
        System.out.println("returned-> " + cookies);
    }
}

And here is the output:

headers-> [Set-Cookie:"TEST=%7B%22keyType%22%3A%22abc%22%2C%22keyValue%22%3A%221.0%22%7D;Max-Age=600;Path=/;Version=0;SameSite=None", Accept-Language:"en-US,en;q=0.9"]
returned-> {Cookie=[$Version="1", TEST="%7B%22keyType%22%3A%22abc%22%2C%22keyValue%22%3A%221.0%22%7D";$Path="/";$Domain="test.com"]}

Why is the format changing? It changes even when I'm passing a serialized cookie too

emilpmp
  • 1,716
  • 17
  • 32
user9517536248
  • 355
  • 5
  • 24

1 Answers1

0

Your "returned" just shows String representation that results from java.net.HttpCookie#toString, documentation says it'd stick to RFC 2965:

//copied from java.net.HttpCookie
private String toRFC2965HeaderString() {
    StringBuilder sb = new StringBuilder();

    sb.append(getName()).append("=\"").append(getValue()).append('"');
    if (getPath() != null)
        sb.append(";$Path=\"").append(getPath()).append('"');
    if (getDomain() != null)
        sb.append(";$Domain=\"").append(getDomain()).append('"');
    if (getPortlist() != null)
        sb.append(";$Port=\"").append(getPortlist()).append('"');

    return sb.toString();
}
Franz Ebner
  • 4,951
  • 3
  • 39
  • 57
  • Thanks for the comment. How come the version value changed and samesite, max-age missing? Can i add a custom cookie handler class where i can override the above behaviour to return the format i want? – user9517536248 Nov 30 '21 at 04:18
  • See ```HttpCookie#guessCookieVersion```, if your header string contains ```version```, ```version``` will be set to ```1```. You should debug the entire process to know why the output is inconsistent. – zysaaa Nov 30 '21 at 09:20