Kousha
Kousha

Reputation: 36209

Jersey consuming both application/json and application/x-www-form-urlencoded

I want to have something like

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

so I can consume both JSON and URL encoded. But when I make a POST request with -d foo=bar I get 415 unsupported formatted error.

Is it possible to consume both using the same endpoint? If it is not possible, how do I do automatic validation for the body for URL encoded? I see people use MultivaluedMap but that's just a map. I want to make sure the right fields are provided.

Upvotes: 0

Views: 1068

Answers (1)

LiorH
LiorH

Reputation: 18824

I believe it's not possible with Jersey (at least I couldn't find an example or documentation for that). But remember you can extract the common logic into a method, and have two methods for the same with different @Consumes directive.

@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)
}

Upvotes: 1

Related Questions