1

我正在测试 CookieManager 上的一些用法,我注意到当我将反序列化的 cookie 传递给 CookieHandler 时,CookieHandler 用于将其放入 cookie 管理器的格式与我传递的格式不同。

示例代码:

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);
    }
}

这是输出:

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"]}

为什么格式会变?即使我也传递了一个序列化的 cookie,它也会改变

4

1 回答 1

0

您的“返回”仅显示来自 的字符串表示java.net.HttpCookie#toString,文档说它会坚持 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();
}
于 2021-11-29T21:20:51.147 回答