java - Spring Boot 在无效的 If-Modified-Since 值上抛出异常

标签 java spring http spring-mvc

抱歉,如果这是错误的地方。

根据定义的 http 规范:https://www.rfc-editor.org/rfc/rfc7232#section-3.3

A recipient MUST ignore the If-Modified-Since header field if the received field-value is not a valid HTTP-date, or if the request method is neither GET nor HEAD.

Spring Boot 不会这样做。它抛出一个 IllegalArgumentException,检查 header 值的代码未处理该异常。

这里是org.springframework.http.HttpHeaders.java中的转换代码

/**
 * Return the value of the {@code If-Modified-Since} header.
 * <p>The date is returned as the number of milliseconds since
 * January 1, 1970 GMT. Returns -1 when the date is unknown.
 */
public long getIfModifiedSince() {
    return getFirstDate(IF_MODIFIED_SINCE);
}

/**
 * Parse the first header value for the given header name as a date,
 * return -1 if there is no value, or raise {@link IllegalArgumentException}
 * if the value cannot be parsed as a date.
 */
public long getFirstDate(String headerName) {
    String headerValue = getFirst(headerName);
    if (headerValue == null) {
        return -1;
    }
    for (String dateFormat : DATE_FORMATS) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
        simpleDateFormat.setTimeZone(GMT);
        try {
            return simpleDateFormat.parse(headerValue).getTime();
        }
        catch (ParseException ex) {
            // ignore
        }
    }
    throw new IllegalArgumentException("Cannot parse date value \"" + headerValue +
            "\" for \"" + headerName + "\" header");
}

因此,如果您发送 header If-Modified-Since:0,您将得到一个异常,而不是返回 http 规范中定义的新 GET 响应。

还有其他人认为这是一个问题吗?

最佳答案

我最近看到了这个 created a ticketsubmitted a PR修复它与此同时,您可以使用过滤器删除 header 来解决此问题,例如

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper((HttpServletRequest) request) {

        @Override
        public Enumeration<String> getHeaderNames() {
            List<String> hdrs = Collections.list(super.getHeaderNames())
                    .stream()
                    .filter(h -> !h.equals(IF_MODIFIED_SINCE))
                    .collect(Collectors.toList());

            return Collections.enumeration(hdrs);
        }
    };
    chain.doFilter(wrapper, response);
}

关于java - Spring Boot 在无效的 If-Modified-Since 值上抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33806370/

相关文章:

Java - 对于在类 A 内定义(静态)的类 B,B.this 意味着什么?

java - SpringMVC自定义集合编辑器不将数据返回到Jsp

java - 如何通过分页按任何字段搜索

java - Groovy 的 Java HTTPBuilder?

http - JMeter -> http 请求 -> POST 参数不能以小写形式工作,并将 POST 更改为大写形式的 GET

java.rmi.ConnectException : Connection refused to host

java - 为什么 Eclipse 报告从 float 到 double 的转换错误

java - 像 IntelliJ 中的 Eclipse 这样的 Alt-left/right arrow key 相当于什么?

spring - Spring Security授权-管理员被拒绝访问

java - 服务器长时间保持连接时http请求会超时吗?