英文:
How parse an http accept header in spring?
问题
我想在Spring中解析HTTP接受头,以确定是否可以返回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;
}
}
}
当请求的接受头值为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是否有一种方法来解析接受头,并确定它是否与特定媒体类型兼容?
英文:
I want to parse an HTTP accept header in Spring to determine if I can send back JSON. I am trying with the following code.
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;
}
}
}
When a request arrives with accept header value of application/json, application/javascript, text/javascript, text/json
I end up with an exception
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)
This code is being used from a Servlet Filter so I can't rely on SpringMVC annotations.
Does Spring has a method for parsing accept header and determining if it is compatible with a specific media type?
答案1
得分: 5
春天本身就像您一样在内部执行此操作(即从请求中获取ACCEPT标头),但他们将其提供给此调用:
MediaType.parseMediaTypes(get(ACCEPT));
这将返回一个您需要处理的 List<MediaType>
。
英文:
Spring itself does it exactly like you internally (i.e. getting the ACCEPT header from the request), but they feed it to this call:
MediaType.parseMediaTypes(get(ACCEPT));
Which will return you a List<MediaType>
that you need to work with.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论