【发布时间】:2019-06-08 11:34:23
【问题描述】:
我收到以下错误;我尝试了一切,但没有得到解决方案:
HTTP Status 415 – Unsupported Media Type
我正在尝试将 JSON 对象发送到控制器,并将其放入 @Requestbody
<%@page import="org.json.JSONObject"%>
<%@ page language="java" contentType="application/json charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome</h1>
<a href="./getRegister">Register</a>
<a href="./delete?id=1">Delete</a>
<%
JSONObject obj = new JSONObject();
obj.put("id", "1");
obj.put("name", "ABC");
%>
<form action="./jsonreq" method="post">
<input type="hidden" name="obj" id="obj" value="<%=obj%>">
<input type="submit" value="Submit"/>
</form>
</body>
</html>
2)控制器:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springhibernate.bean.Employee;
import com.springhibernate.service.EmployeeService;
@Controller
public class RegistrationController {
@RequestMapping(path="/jsonreq", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Employee json(@RequestBody Employee obj)
{
System.out.println("JSON"+obj.toString());
return obj;
}
}
【问题讨论】:
-
因为
"json"不是一个有效的MIME类型 - 你想要"application/json",它也可以作为MediaType.APPLICATION_JSON_VALUE使用。 -
@jonrsharpe:试过了,但现在我收到错误 ``` HTTP 状态 415 – 不支持的媒体类型 ```
-
那么您实际上提出了什么要求? “我正在尝试发送 JSON” - 你是吗? 是是
application/json吗?如果没有,您为什么不编写一个端点来处理您实际发送的内容?至少,您应该能够将问题范围缩小到问题出在客户端还是服务器上。 -
@jonrsharpe:我正在将表单隐藏字段中的 json 对象发送到控制器......并且在控制器中,我希望 json 对象与我的 Employee Bean Obj 映射
-
你是吗?请查看您的网络选项卡并查看您实际发送的内容。为什么您会收到 415 的简短答案是,正如错误消息告诉您的那样,服务器不支持客户端发送的请求的媒体类型。
标签: json spring spring-mvc spring-rest