【问题标题】:HttpHeaders getFirst() case insensitivityHttpHeaders getFirst() 不区分大小写
【发布时间】:2018-09-07 14:17:13
【问题描述】:

我正在使用 Spring 的 RestTemplate 获取 HTTP 标头。

HTTP headers are case insensitive,但documentation for HttpHeaders 似乎并不承认这一点。

快速测试表明一切正常...

HttpHeaders headers = restTemplate.headForHeaders(url);
Long a = Long.parseLong(headers.getFirst("Content-Length"));
Long b = Long.parseLong(headers.getFirst("content-length"));
assert( a.equals(b) ); // passes

我能确定这个测试在所有 Spring 配置下都能通过吗?

【问题讨论】:

    标签: java spring http-headers resttemplate


    【解决方案1】:

    this commit 明确指出 HttpHeaders 不区分大小写:

    请注意,HttpHeaders 通常以不区分大小写的方式处理标题名称。


    旧答案

    HttpHeaders 只有一个公共构造函数及其主体:

    public HttpHeaders() {
        this(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH), false);
    }
    

    根据LinkedCaseInsensitiveMapdocs

    以不区分大小写的方式存储字符串键的 LinkedHashMap 变体,例如用于结果表中基于键的访问。

    保留键的原始顺序和原始大小写,同时允许使用任何大小写的键进行包含、获取和删除调用

    所以是的,它总是以不区分大小写的方式工作。

    但是你为什么不使用HttpHeaders#getContentLength()? :

    // no need to convert String to long
    long contentLength = httpHeaders.getContentLength();
    

    【讨论】:

      猜你喜欢
      • 2012-12-01
      • 2013-03-06
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 2016-11-24
      • 2011-03-08
      相关资源
      最近更新 更多