代码之家  ›  专栏  ›  技术社区  ›  Kousha

Jersey同时使用application/json和application/x-www-form-urlencoded

  •  0
  • Kousha  · 技术社区  · 6 年前

    我想要一些像

    @POST
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED})
    @Path("/")
    void create(@Suspended final AsyncResponse asyncResponse,
                @ApiParam(required = true) @NotNull @Valid final CreateServiceRequest service);
    

    所以我可以同时使用JSON和URL编码。但是当我向 -d foo=bar 我得到415不支持的格式化错误。

    是否可以使用同一个端点同时使用两者?如果不可能,我如何对URL编码的主体进行自动验证?我看到人们用 MultivaluedMap 但那只是一张地图。我要确保提供正确的字段。

    1 回复  |  直到 6 年前
        1
  •  1
  •   LiorH    6 年前

    我相信在泽西岛是不可能的(至少我找不到相关的例子或文档)。 但请记住,您可以将常见的逻辑提取到一个方法中,并且有两个方法针对同一个方法和不同的方法 @Consumes 指令。

    @POST
    @Consumes({MediaType.APPLICATION_JSON})
    @Path("/")
    void createJson(@Suspended final AsyncResponse asyncResponse,
                            @ApiParam(required = true) @NotNull @Valid final CreateServiceRequest service) {
        create(service)
    }
    
    
    @POST
    @Consumes({MediaType.APPLICATION_FORM_URLENCODED})
    @Path("/")
    void createJson(@Suspended final AsyncResponse asyncResponse,
                            @ApiParam(required = true) @NotNull @Valid final CreateServiceRequest service) {
        create(service)
    }