如何获取REST-Request请求的contenttype?
How to get the requested contenttype of a REST-Request?
使用 JAXB 实现 REST-Webservice,我们有几个方法正在生成输出。
包含所有这些方法的class被注释为@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
。如果请求进入 happy-path(没有错误发生),我们 return 我们方法中的 POJO 和 JAXB 动态地将这些 objects 编组为 application/xml
或 application/json
,因为客户端在请求 header.
中通过 Accept: application/xxx;
请求了它
我的问题是如何获取请求的内容类型,因为如果发生错误,我们将抛出一个 WebApplicationException
响应,其中应包含格式化为请求的内容类型的自定义错误消息。
你可以...
注入@HeaderParam("Accept")
public Response doSomething(@HeaderParam("Accept") String accept) {
// you may need to parse it as the value is not always as
// simple as application/json
}
你可以...
注入 HttpHeaders
,您有几个选择
public Response doSomething(@Context HttpHeaders headers) {
String accept = headers.getHeaderString(HttpHeaders.ACCEPT);
List<MediaType> acceptableType = headers.getAcceptableMediaTypes();
}
使用 JAXB 实现 REST-Webservice,我们有几个方法正在生成输出。
包含所有这些方法的class被注释为@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
。如果请求进入 happy-path(没有错误发生),我们 return 我们方法中的 POJO 和 JAXB 动态地将这些 objects 编组为 application/xml
或 application/json
,因为客户端在请求 header.
Accept: application/xxx;
请求了它
我的问题是如何获取请求的内容类型,因为如果发生错误,我们将抛出一个 WebApplicationException
响应,其中应包含格式化为请求的内容类型的自定义错误消息。
你可以...
注入@HeaderParam("Accept")
public Response doSomething(@HeaderParam("Accept") String accept) {
// you may need to parse it as the value is not always as
// simple as application/json
}
你可以...
注入 HttpHeaders
,您有几个选择
public Response doSomething(@Context HttpHeaders headers) {
String accept = headers.getHeaderString(HttpHeaders.ACCEPT);
List<MediaType> acceptableType = headers.getAcceptableMediaTypes();
}