Java 使用@RequestBody 启动不受支持的媒体类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44230121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:25:36  来源:igfitidea点击:

Spring boot Unsupported Media Type with @RequestBody

javaspring

提问by jodekpotasu

I checked in several different ways, also downloaded a new project to see what to check where is bug but I still do not know the answer.

我检查了几种不同的方式,还下载了一个新项目来查看要检查的错误在哪里,但我仍然不知道答案。

That is my RestController

那是我的 RestController

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

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

That is my Model

那是我的模型

@Data
@Entity
public class Message {

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

    private String sender;
    private String telephone;
    private String message;
}

Gradle dependencies if necessary

如有必要,Gradle 依赖项

dependencies {
    compile group: 'com.fasterxml.Hymanson.core', name: 'Hymanson-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')
}

and in postman i'm getting that error

在邮递员中,我收到了那个错误

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

{ "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/" }

It is simplest way for rest but where I make a mistake?

这是最简单的休息方式,但我哪里出错了?

回答by user2618324

The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBodyannotation.

问题在于,当我们使用 时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
    }

回答by adeshina.O

In Postman. under Body, select rawand choose JSON from the drop down menu that appears. Then write the JSON that is the request body. You can't use form-dataor x-www-form-urlencodedwith @RequestBody, they are used when the binding is @ModelAttribute.

在邮递员。在 下Bodyraw从出现的下拉菜单中选择并选择 JSON。然后编写作为请求正文的 JSON。您不能使用form-datax-www-form-urlencodedwith @RequestBody,它们在绑定为 时使用@ModelAttribute

回答by VK321

I had a similar issue using $.postJquery. By adding correct contentTypeand dataTypeit worked for me.

我在使用$.postJquery 时遇到了类似的问题。通过添加正确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);
    }
});

回答by Ankit Kesharwani

You can write the code as
headers.put("Content-Type", Arrays.asList("application/json"));
instead of
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

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

回答by user12858831

I got the same case with Json. Finally only this works Here code on react

我和 Json 遇到了同样的情况。最后只有这个有效 这里代码反应

export function setServices(jsonString) {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json;charset=UTF-8;");

var raw = jsonString;

var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: raw,
    redirect: 'follow'
};

fetch("http://localhost:8080/setservices", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));}

Code on controller

控制器上的代码

@RequestMapping(value = "/setservices", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody  String createMessage() throws Exception {
    //do smthg

    return "Ok";    }