想象一下我的资源可以通过/rest/properties/<key>/data
支持的内容类型取决于属性类型。
对于 GET 这没问题:(运行时内容协商)
@GET
public Response readData(@PathParam("key") String key) {
MyProperty property = getProperty(key);
List<Variant> variants = property.getType().getVariants();
Variant variant = request.selectVariant(variants);
if (null == variant) {
return Response.notAcceptable(variants).build();
}
return Response.ok(property.getData(), variant).build();
// -> registered @Provider (MessageBodyWriter) will be called
}
现在我想要一个“Consumes”的等价物用于 POST/PUT。
定义几种方法的常用方法不是一个选项,因为我需要先计算类型:
所以目标是这样的:
@POST
public Response updateData(@PathParam("key") String key, InputStream is) {
MyProperty property = getProperty(key);
List<Variant> variants = property.getType().getVariants();
Variant variant = /* get request content type */;
if (!variants.contains(variant)) {
return Response.status(415).build();
}
entity = /* delayed MessageBodyReader call?!
readFrom(is, variant , ExpectedClass.class);
*/
... save entity in db or fs
return Response.ok().build();
}
顺便说一句,常见的方法是: [不会编译(消费媒体类型冲突)]
@POST
@Consumes("text/plain")
public Response updateDataPlain(@PathParam("key") String key, ExpectedClass entity) {
... save entity in db or fs
return Response.ok().build();
}
@POST
@Consumes("text/plain")
public Response updateDataPlain(@PathParam("key") String key, AnotherExpectedClassWhichSupportPlain entity);