【问题标题】:Spring Boot 2.1.2 + POSTMAN + 415 Unsupported Media "application/json"Spring Boot 2.1.2 + POSTMAN + 415 Unsupported Media "application/json"
【发布时间】:2019-08-22 14:17:29
【问题描述】:

我知道这个问题得到了多次回答,但不知何故我无法通过它。另外,我没有发现 Unsupported Media "application/json" 错误。

编辑:@RequestBody 在我在 POSTMAN 中选择 x-www-form-urlencoded 时有效,但不适用于 raw -> application/json

我只想通过 POSTMAN 发布数据来创建记录。

这是我的代码:

Spring Boot 版本:2.1.2

我读到 jackson 数据绑定已经存在于 2.1.2 版本的 spring boot 中。

邮递员请求:

Body -> raw -> application/json

{
  "first_name": "ashutosh",
  "middle_name": "",
  "last_name": "pandey",
  "gender": "male",
  "address": "my address"
}

{
  "firstName": "ashutosh",
  "middleName": "",
  "lastName": "pandey",
  "gender": "male",
  "address": "my address"
}

{
  "practitioner": {
  "first_name": "ashutosh",
  "middle_name": "",
  "last_name": "pandey",
  "gender": "male",
  "address": "my address"
  }
}

邮递员标题:

Content-Type: application/json
Accept: application/json 

Spring Boot 控制器

@RestController
@RequestMapping("/practitioner")
public class PractitionerController{
@Autowired private CrudService<Practitioner> crudService;

/**
 * POST /create --> Create a new Practitioner and save it in the database.
 */
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> create(@RequestBody Practitioner practitioner) 
{
    crudService.save(practitioner);
    String practitionerId = String.valueOf(practitioner.getId());
    return ResponseEntity.ok().body(practitionerId);
}
}

我的实体

package auto.nicu.entity;

import java.io.Serializable;
import java.util.Date;
import java.util.Set;

import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GenerationType;
import javax.persistence.GeneratedValue;

@Entity
@Table(name="practitioners")
public class Practitioner implements Serializable{
private static final long serialVersionUID = 6017382414498150143L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id") private Integer id;

@Column(name="gender", length=256) private String gender;
@Column(name="address", length=256) private String address;
@Column(name="last_name", length=256) private String lastName;
@Column(name="first_name", length=256) private String firstName;
@Column(name="middle_name", length=256) private String middleName;

@OneToMany(mappedBy="practitioner") Set<PractitionerAction> practitionerActions;

public Practitioner() {}

/************* Getters *******************/

public Integer getId() {  return id; }  

public String getGender() {  return gender; }
public String getAddress() {  return address; }
public String getLastName() {  return lastName; }
public String getFirstName() {  return firstName; }
public String getMiddleName() {  return middleName; }

public Set<PractitionerAction> getPractitionerActions() {  return practitionerActions; }

/************* Setters *******************/

public void setId(Integer id) { this.id = id; }

public void setGender(String gender) { this.gender = gender; }
public void setAddress(String address) { this.address = address; }
public void setLastName(String lastName) { this.lastName = lastName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public void setMiddleName(String middleName) { this.middleName = middleName; }

public void setPractitionerActions(Set<PractitionerAction> practitionerActions) { this.practitionerActions = practitionerActions; }
}

无论我做什么,我总能得到:

{"timestamp":"2019-04-01T11:46:15.420+0000","status":415,"error":"Unsupported Media Type","message":"Content type 'application/json;charset=UTF-8' not supported","trace":"org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:224)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:157)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:130)\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:126)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:166)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter....

我尝试删除@RequestBody,添加了consumes="application/json" 或consumes=MediaType.APPLICATION_JSON_VALUE,错误消失了,但我在数据库中得到了空值。

我尝试创建一个简单的 html 表单并使用 jquery 提交数据,但同样的错误:(

  <script type="text/javascript">
$(function(){
    $("#btn").click(function(){
        $.ajax({
            url: 'http://localhost:8080/practitioner/',
            method: 'post',
            data: $("#form").serialize(),
            dataType: 'json',
            headers: {
                'Authorization':'Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6ImFkbWluIiwiaWF0IjoxNTU0MTcxNzA0fQ.o7AYTb8sE0iT5YMLndPUnkvdK5-sWG3u26gfK9z56ls',
                'Content-Type':'application/json'
            },
            success: function(result){
                console.log(result);
            }
        });
    });
});
</script>

这是一个误导性错误吗?

这是错误堆栈跟踪:

{"timestamp":"2019-04-02T02:29:27.522+0000","status":415,"error":"Unsupported Media Type","message":"Content type 'application/json;charset=UTF-8' not supported","trace":"org.springframework.web.HttpMediaTypeNotSupportedException: 
Content type 'application/json;charset=UTF-8' not supported\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:224)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:157)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:130)\n\tat     
org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:126)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:166)\n\tat 
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\n\tat 
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:660)\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\n\tat 
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat 
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)\n\tat org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)\n\tat org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\n\tat 
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\n\tat 
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\n\tat org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\n\tat 
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\n\tat org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)\n\tat 
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\n\tat org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\n\tat org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)\n\tat 
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\n\tat org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\n\tat 
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\n\tat org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)\n\tat org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)\n\tat 
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)\n\tat org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat 
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat 
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\n\tat 
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\n\tat java.lang.Thread.run(Thread.java:748)\n","path":"/practitioner/"}

【问题讨论】:

    标签: spring-boot postman


    【解决方案1】:

    这里有很多问题。我会尝试:

    1. 从 Postman 中删除“接受:应用程序/json”。此标头表示客户端仅接受“application/json”作为响应类型
    2. 在@PostMapping 中删除 (headers="Accept=application/json")
    3. 删除@ResponseBody,因为@RestController 中不需要它

    您的从业者课程的内容是什么?您的 Postman 请求的路径是 /practitioner ?

    【讨论】:

    • 试过但同样的问题 :( ,在上面添加了 Practitioner 类
    • 您应该在 Postman 中使用第一个主体(没有“从业者”)。名称(firstName、middleName、lastName)使用驼峰式大小写作为 objectMapper 的默认配置使用 getter/setter 进行序列化/反序列化您也可以发布异常堆栈跟踪吗?
    • 嗨@htn,添加了堆栈跟踪
    • 是的,路径是/practitioner
    • 你应该从服务器端发布堆栈跟踪,这样更容易阅读。如果错误消失了,请在控制器方法中使用 debug 来了解它为什么不起作用。
    【解决方案2】:

    在这里查看一些可能的原因:http://javahonk.com/415-unsupported-media-type/

    【讨论】:

      【解决方案3】:

      Change @PostMapping(headers="Accept=application/json") for @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)

      同样在 Postman 中使用请求用户 CammelCase 而不是 _

      举例

      用户 firstName 而不是 first_name, 或

      您可以将JsonProperties 设置为Practitioner 以接收您想要的属性。

      【讨论】:

      • 更新代码,删除标题,添加消耗,现在使用驼峰式大小写,添加堆栈跟踪,仍然错误:(
      猜你喜欢
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 2012-07-14
      • 2020-01-02
      • 2020-05-05
      • 2022-10-13
      • 2018-06-10
      • 2015-07-25
      相关资源
      最近更新 更多