[英]HTTP Status 415 – Unsupported Media Type when doing POST request on Spring MVC
我试图在简单的Spring MVC Web应用程序上发送发布请求,并在控制器中使用RequestBody
将JSON转换为Java对象,但是由于任何原因,我一直收到HTTP Status 415 – Unsupported Media Type
。 我花了很多时间试图找到解决方案,但是似乎没有任何效果。
我的控制器中的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
批注中的消费值,并且尝试了请求@RequestMapping
头accept和Content type的所有组合。
另外,如果我使用@ModelAttribute
而不是@RequestBody
,那么一切正常,除了Contact
类中的所有字段均为空。
这是github链接-https: //github.com/Sanil2108/test_springmvc
对我来说,jpa注释似乎弄乱了json反序列化。
从Spring服务器返回的错误可能会引起误解。 尝试使用带有setter和getter的普通对象,看看这是否有任何改变。 您应该在日志中搜索一些例外。
将映射添加到handleGet
方法,例如:
@RequestMapping(value = "/get", method = RequestMethod.GET, consumes = "application/json")
public void handleGet() {
System.out.println("a");
}
--UPDATE--
从GET调用中删除consumes = "application/json"
部分。 它看到两个侦听“ / users”的请求都可以使用json数据,但是一个请求是GET,另一个请求是POST。
-第2次更新-这肯定可以。 测试。
@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);
}
}
RequestMapping
注释不仅具有consumes
而且具有produces
。
但是要避免针对HTTP REST的所有这些设置,可以使用RestController
注释和GetMapping
, PostMapping
等。
你可以在我的github上找到一个例子
尝试了所有内容,但无法正常工作。 也许我在某个地方犯了一个愚蠢的错误,或者我的配置存在严重错误。 无论如何,我试图使其与Spring boot一起使用,并且工作正常。 对于任何有兴趣的人,这里是github链接-https: //github.com/Sanil2108/spring_hibernate/tree/master/spring_boot1
另外,感谢所有尝试提供帮助的人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.