Spring引导不支持的媒体类型与@RequestBody

jod*_*asu 8 java spring

我检查了几种不同的方式,还下载了一个新项目,看看有什么检查bug,但我仍然不知道答案.

那是我的RestController

@RestController
@RequestMapping(value = "/message")
public class MessageController {

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public void createMessage(@RequestBody Message message){
        System.out.println(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

那是我的模特

@Data
@Entity
public class Message {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String sender;
    private String telephone;
    private String message;
}
Run Code Online (Sandbox Code Playgroud)

必要时Gradle依赖项

dependencies {
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.0.pr3'
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-web')
    runtime('com.h2database:h2')
    runtime('org.postgresql:postgresql')
    compileOnly('org.projectlombok:lombok')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}
Run Code Online (Sandbox Code Playgroud)

在邮递员我得到了那个错误

{"timestamp":1495992553884,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException",
"message":"Content type'application/x-www -form-urlencoded; charset = UTF-8'不支持",
"path":"/ message /"}

这是最简单的休息方式,但我犯了错误?

ade*_*a.O 16

在Postman中,在Body下,Body从出现的下拉菜单中选择并选择JSON,然后编写作为请求主体的JSON,不能使用rawform-data使用@RequestBody,它们在绑定为@ModelAttribute时使用.

  • 谢谢你,小伙伴。对于使用 POSTMAN 的人来说,你有正确的答案...... (2认同)

小智 7

问题在于,当我们使用 时application/x-www-form-urlencoded,Spring 并不将其理解为 RequestBody。所以,如果我们想使用它,我们必须删除@RequestBody注释。

@RequestMapping(value = "/", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void createMessage(Message message){
        //TODO DO your stuff here
    }
Run Code Online (Sandbox Code Playgroud)

  • 我的配置是。消耗= MediaType.APPLICATION_JSON_VALUE,产生= MediaType.APPLICATION_JSON_VALUE 我仍然遇到这个问题 (2认同)

VK3*_*321 5

我在使用 Jquery 时遇到了类似的问题$.post。通过添加正确的内容contentTypedataType它对我有用。

$.ajax({
    type: "POST",
    url: "/api/design/save",
    data: JSON.stringify({
        id: floorId,
        shapes: shapes,
    }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
        console.log(data);
   },
    error: function(err) {
        console.log(err);
    }
});
Run Code Online (Sandbox Code Playgroud)

  • contentType: "application/json; charset=utf-8",解决了我的问题。 (3认同)

小智 5

您可以编写代码
headers.put("Content-Type", Arrays.asList("application/json"));
,而不是
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));


小智 5

您需要一个 @NoArgsConstructor 才能使反序列化工作。如果不存在无参数构造函数,则 Http 消息转换器无法将 json(其他媒体类型)映射到 Java 对象。返回 415