gkatzioura
gkatzioura

Reputation: 2820

HttpMediaTypeNotSupportedException on mockmvc post

I have a RestController and a function that accepts post requests

@RequestMapping(path = "/auth",method = RequestMethod.POST)
public void authenticate(@RequestBody AuthenticationRequest authenticationRequest, HttpServletResponse httpServletResponse) throws  IOException {
}

I try to issue a post request

mockMvc.perform(post("/auth")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content("{ \"foo\": \"bar\", \"fruit\": \"apple\" }".getBytes()))
            .andDo(print());

I receive

Resolved Exception:
         Type = org.springframework.web.HttpMediaTypeNotSupportedException

Any workaround ideas?

Edit: I also tried specifying the consumes="application/json" on the controller, but still does not work.

Upvotes: 2

Views: 1021

Answers (1)

Benjamin Peter
Benjamin Peter

Reputation: 4038

The Exception says that the "media type" aka "content type" is not accepted.

Try adding consumes = "application/json" to your controller function.

@RequestMapping(path = "/auth",method = RequestMethod.POST,consumes = "application/json")
public void authenticate(@RequestBody AuthenticationRequest authenticationRequest, HttpServletResponse httpServletResponse) throws  IOException {
}

See the spring documentation for details https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html#consumes--

Upvotes: 1

Related Questions