我检查了几种不同的方式,还下载了一个新项目,看看有什么检查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,不能使用raw或form-data使用@RequestBody,它们在绑定为@ModelAttribute时使用.
小智 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)
我在使用 Jquery 时遇到了类似的问题$.post。通过添加正确的内容contentType,dataType它对我有用。
$.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)
小智 5
您可以编写代码
headers.put("Content-Type", Arrays.asList("application/json"));
,而不是
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
| 归档时间: |
|
| 查看次数: |
24257 次 |
| 最近记录: |