【问题标题】:Why am I getting 415 Unsupported Media Type in Spring MVC?为什么我在 Spring MVC 中得到 415 Unsupported Media Type?
【发布时间】: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


【解决方案1】:

您收到 415 状态是因为您的浏览器正在向仅接受 application/json 的控制器方法发送内容类型为 application/x-www-form-urlencoded 的请求。

问问自己是否真的需要以这种方式发送 JSON 数据,而不是作为表单的一部分。

如果您这样做了,实现它的一种方法是使用 Javascript 将表单(或其他地方)中的数据编译为 JSON,并制作一个 XMLHttpRequest 将其发布到您的服务器。

另一种不太理想的方法是删除控制器方法上的 consumes 约束,将参数更改为 @RequestParam("obj") String obj 并使用 Autowired ObjectMapper 使用 objectMapper.readValue(obj, Employee.class) 手动解析控制器方法中的响应。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 2022-10-13
    • 2020-02-18
    • 2015-07-25
    • 2021-07-16
    相关资源
    最近更新 更多