在用spring开发rest接口,表单提交用的put方式,content-type是application/x-www-form-urlencoded
代码如下
@RequiresPermissions("act:model:edit")
@RequestMapping(value = "/act/service/model/{modelId}/save", method = RequestMethod.PUT)
@ResponseStatus(value = HttpStatus.OK)
public void saveModel(@PathVariable String modelId, @RequestBody MultiValueMap<String, String> values) {
try {
Model model = repositoryService.getModel(modelId);
ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
@RequiresPermissions("act:model:edit")
@RequestMapping(value = "/act/service/model/{modelId}/save", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void saveModel(@PathVariable String modelId, @RequestBody MultiValueMap<String, String> values) {
try {
Model model = repositoryService.getModel(modelId);
ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
用restful client测试,一直报400,参数解析错误,跟踪代码到spring核心包,
HttpServletRequest servletRequest = (HttpServletRequest)webRequest.getNativeRequest(HttpServletRequest.class);
ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest);
InputStream inputStream = inputMessage.getBody();
。。。
final PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
int b = pushbackInputStream.read();
if(b == -1) {
return this.handleEmptyBody(methodParam);
}
抛出了requestbody为空的异常。原因是在inputMessage.getBody()的时候就是错的
ServletServerHttpRequest
public InputStream getBody() throws IOException {
return (InputStream)(isFormPost(this.servletRequest)?getBodyFromServletRequestParameters(this.servletRequest):this.servletRequest.getInputStream());
}
private static boolean isFormPost(HttpServletRequest request) {
String contentType = request.getContentType();
return contentType != null && contentType.contains("application/x-www-form-urlencoded") && "POST".equalsIgnoreCase(request.getMethod());
}
分析可得:spring要求使用application/x-www-form-urlencoded方式提交的表单要用post方式