在Spring MVC上执行POST请求时,HTTP状态415 –不支持的媒体类型

时间:2018-10-07 09:32:07

标签: java spring spring-mvc content-type

我试图在一个简单的Spring MVC Web应用程序上发送一个发布请求,并在我的控制器中使用RequestBody将JSON转换为Java对象,但是由于某种原因,我一直得到HTTP Status 415 – Unsupported Media Type。我花了很多时间试图找到解决方案,但是似乎没有任何效果。

我的Controller中的get方法似乎工作正常。这是我的原始代码

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(value = "/users", method = RequestMethod.POST)
public class MyControllerAgain {

    @RequestMapping(method = RequestMethod.POST, consumes = "application/json")
    public void handleJson(@RequestBody Contact c) {
        System.out.println(c);
    }

    @RequestMapping(method = RequestMethod.GET, consumes = "application/json")
    public void handleGet() {
        System.out.println("a");
    }
}

这是我的Contact

public class Contact {

    int id;

    public String name;

    public int number;

    public Contact(){}

    // Getters and setters
}

我正在与邮递员发送请求,这就是它的样子

POST /users HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Accept: application/json
Cache-Control: no-cache
Postman-Token: 511c9e03-4178-380d-58f8-db24a3245b9e

{
    "id":1,
    "name":"something",
    "number":1
}

我还尝试过在我的pom.xml中包括Jackson依赖项。 我尝试更改@RequestMapping批注中的消费值,并且尝试了请求中标头accept和Content type的所有组合。

此外,如果我使用@ModelAttribute而不是@RequestBody,那么一切正常,除了Contact类中的所有字段均为空。

这是github链接-https://github.com/Sanil2108/test_springmvc

4 个答案:

答案 0 :(得分:0)

对我来说,jpa注释似乎弄乱了json反序列化。

spring服务器返回的错误可能会引起误解。 尝试使用带有setter和getter的普通对象,看看这是否有任何改变。 您应该在日志中搜索一些例外情况。

答案 1 :(得分:0)

将映射添加到handleGet方法,例如:

@RequestMapping(value = "/get", method = RequestMethod.GET, consumes = "application/json")
public void handleGet() {
    System.out.println("a");
}

-更新-

从GET调用中删除consumes = "application/json"部分。可以看到,两个请求都可以侦听“ / users”请求,但可以使用json数据,但一个是GET,另一个是POST。

-2nd更新- 这肯定会工作。经过测试。

@RestController
@RequestMapping(value = "/users", method = RequestMethod.POST)
public class ContactController
{
    @RequestMapping(method = RequestMethod.POST, consumes = "application/json")
        public void handleJson(@RequestBody Contact c) 
        {
           System.out.println(c);
        }
}

答案 2 :(得分:0)

RequestMapping注释不仅具有consumes,而且具有produces

但是要避免对HTTP REST进行所有这些设置,可以使用RestController批注以及GetMappingPostMapping等。

您可以在我的github

中找到一个示例

答案 3 :(得分:0)

尝试了所有内容,但无法正常工作。也许我在某个地方犯了一个愚蠢的错误,或者我的配置存在严重错误。无论如何,我试图使其与Spring boot一起使用,并且工作正常。对于任何有兴趣的人,这是github链接-https://github.com/Sanil2108/spring_hibernate/tree/master/spring_boot1

还要感谢所有尝试提供帮助的人!

相关问题