gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:53:43 25 4
gpt4 key购买 nike

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

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

A recipient MUST ignore the If-Modified-Since header field if thereceived field-value is not a valid HTTP-date, or if the requestmethod 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com