415 Unsupported MediaType for POST request in spring application

时光毁灭记忆、已成空白 提交于 2019-11-28 11:05:12
Tahir Hussain Mir

Accept Header might be the issue. As far as i remember, when you send a request via curl it adds a default header accept : */*
But in case of JSON you have to mention the accept header
as accept : application/json
similarly you have mentioned the content-Type.

And little more, i dont know what is that, but don't you think you have to place "request mappings" like that

@RequestMapping(value="/sample" ...
@RequestMapping(value="/sample2" ...

This may not be the case, but accept header is the thing, i think is the main issue.
Solution 2
Since you have this code

public String getResponse2(@RequestBody Person person)

I have already faced this problem before and the solution two may help here

FormHttpMessageConverter which is used for @RequestBody-annotated parameters when content type is application/x-www-form-urlencoded cannot bind target classes as @ModelAttribute can). Therefore you need @ModelAttribute instead of @RequestBody

Either Use @ModelAttribute annotation instead of @RequestBody like this

public String getResponse2(@ModelAttribute Person person)

I provided the same answer to somebody and it helped. here is that answer of mine

I found the solution and I want to post here so it benefits others.

Firstly I need to include jackson in my classpath, which I added in build.gradle as follows:

 compile 'com.fasterxml.jackson.core:jackson-databind:2.7.5'
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.5'
    compile 'com.fasterxml.jackson.core:jackson-core:2.7.5'

Next, I have to change my AppConfig which extends WebMvcConfigurerAdapter as follows:

@Configuration
@EnableWebMvc
@ComponentScan("com.example.myApp")
public class AppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/test/**").addResourceLocations("/test/").setCachePeriod(0);
        registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(0);
        registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(0);
        registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(0);
    }


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        converters.add(new MappingJackson2HttpMessageConverter());
        super.configureMessageConverters(converters);
    }
}

That is all and everything worked nicely

can you trying using the -d option in curl

curl -H "Content-Type: application/json" -X POST -d
 '{"id":"1,"name":"sai"}'
 http://localhost:8095/myApp/service/example/sample2

Also, if you use windows you should escape double quotes

-d "{ \"id\": 1, \"name\":\"sai\" }" 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!