gpt4 book ai didi

java - spring中如何解析http接受 header ?

转载 作者:行者123 更新时间:2023-12-02 08:52:20 24 4
gpt4 key购买 nike

我想在 Spring 中解析 HTTP 接受 header 以确定是否可以发回 JSON。我正在尝试使用以下代码。

class MediaTypeUtil {
private final static Logger logger = LoggerFactory.getLogger(MediaTypeUtil.class);
static boolean acceptsJson(HttpServletRequest request) {
try {
String accept = request.getHeader("Accept");
MediaType requestType = MediaType.valueOf(accept);
return MediaType.APPLICATION_JSON.isCompatibleWith(requestType);
} catch (InvalidMediaTypeException e) {
logger.debug("MediaType parsing error",e);
return false;
}
}
}

当请求到达时接受 header 值为 application/json、application/javascript、text/javascript、text/json 时,我最终会遇到异常

Caused by: org.springframework.util.InvalidMimeTypeException: Invalid mime type "application/json, application/javascript, text/javascript, text/json": Invalid token character ',' in token "json, application/javascript, text/javascript, text/json"
at org.springframework.util.MimeTypeUtils.parseMimeTypeInternal(MimeTypeUtils.java:262)

这段代码是从 Servlet 过滤器中使用的,所以我不能依赖 SpringMVC 注释。

Spring有解析accept头并确定它是否与特定媒体类型兼容的方法吗?

最佳答案

Spring 本身在内部的做法与您完全一样(即从请求中获取 ACCEPT header ),但它们将其提供给此调用:

MediaType.parseMediaTypes(get(ACCEPT));

这将返回给您 List<MediaType>您需要与之合作。

关于java - spring中如何解析http接受 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60695858/

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