首页 > 解决方案 > PUT 请求的 Spring Boot 406 状态码

问题描述

代码是

@RestController
@Component
@Slf4j
public class ServicesController {
 @CrossOrigin
    @PutMapping(
            consumes = "multipart/form-data",
            path = "/{id}/{route}/structure_article/{filename:.+}")
    public ResponseEntity<ServiceResponse> updateStructureXMLFile(
            @PathVariable("id") final String id,
            @PathVariable("route") final String route,
            @RequestParam("file") final MultipartFile uploadfile,
            @PathVariable("filename") final String fileName) throws IOException {
(Some processing)
return new ResponseEntity<>(response, httpHeaders, HttpStatus.CREATED);
}
}

这里的响应是一个带有公共 getter 和 setter 的 POJO。 在此处输入图像描述

当我放置文件时出现此错误:

{
    "timestamp": 1596783608973,
    "status": 406,
    "error": "Not Acceptable",
    "exception": "org.springframework.web.HttpMediaTypeNotAcceptableException",
    "message": "Could not find acceptable representation",
    "path": "/7f3033d7-3979-45e0-9f0a-172b60568edb/articles/structure_article/manuscript.xml"
}

有什么办法可以解决这个问题?谢谢

标签: javaspring-bootputhttp-status-code-406

解决方案


就我而言,内容协商的配置如下:

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer
        .favorPathExtension(true)
        .defaultContentType(MediaType.APPLICATION_JSON)
        .mediaType("xml", MediaType.APPLICATION_XML) 
        .mediaType("json", MediaType.APPLICATION_JSON); 
}

和你一样,我有一个控制器方法

@PutMapping("/user/{userId:.+}")

因此,Spring 尝试使用 Common MIME 类型中不存在的文件扩展名来处理请求/user/email@domain.com因此出现Content-Type406错误。.com

我通过关闭来解决它favorPathExtension


推荐阅读