【问题标题】:Http Put request with content type application/x-www-form-urlencoded not working in Spring内容类型为 application/x-www-form-urlencoded 的 Http Put 请求在 Spring 中不起作用
【发布时间】:2019-03-06 16:50:03
【问题描述】:

我有一个 spring-boot 应用程序,它唯一做的就是接收 http 请求。

这是我的弹簧控制器:

@RestController
public class WebController {

    @Autowired
    private CallRecording callRecording;

    @PutMapping(path = "/cdrpostbox/callrecording/{hostedAccountId}/{mp3FileName}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<Object> callRecording(@PathVariable("hostedAccountId") String hostedAccountId, @PathVariable("mp3FileName") String mp3FileName, MultipartFile file) {
        return ResponseEntity.status(callRecording.service(hostedAccountId, mp3FileName, file)).body(null);
    }

}

我正在使用 Postman 发送请求。我的 Spring 应用程序收到的请求无法更改,因为代码不是由我的团队维护的。

request headers

request body

我在这里发现了很多关于类似问题的问题,但与我必须解决的问题并不完全相同。我尝试添加和删除 @RequestBody ,将 @RequestBody 替换为 @RequestParam,我尝试了 MultiValueMap,但它一直返回同样的错误。

java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "x"

我什至无法调试代码,因为它在到达控制器之前就失败了。

我错过了什么?

【问题讨论】:

    标签: java spring spring-boot spring-mvc postman


    【解决方案1】:

    header 中的 content-type 是 urlencoded,但是你发送的是二进制数据。

    --- 编辑

    如果您想将文件作为 MultipartFile 获取,则将文件作为表单数据从邮递员发送,将数据名称设置为文件,并将 @RequestParam 添加到方法中的文件参数。

    【讨论】:

    • 我更改了我的请求,我现在不发送标头。我还更改了我的控制器@PutMapping(path = "/cdrpostbox/callrecording/{hostedAccountId}/{mp3FileName}") public ResponseEntity&lt;Object&gt; callRecording(@PathVariable("hostedAccountId") String hostedAccountId, @PathVariable("mp3FileName") String mp3FileName, MultipartFile requestBody) {,但现在 requestBody 为空。这个问题的解决方案是什么?
    • 我也发现这个问题和我问的一样stackoverflow.com/questions/40000409/…
    • 您的请求现在不是多部分请求。将最后一个参数更改为@RequestBody byte[] requestBody
    【解决方案2】:

    经过一番调查,我找到了解决方案。

    @RestController
    @EnableWebMvc
    public class WebController {
    
        @Autowired
        private CallRecording callRecording;
    
        @PutMapping(path = "/cdrpostbox/callrecording/{hostedAccountId}/{mp3FileName:.+}")
        public ResponseEntity<Object> callRecording(@PathVariable("hostedAccountId") String hostedAccountId, @PathVariable("mp3FileName") String mp3FileName, @RequestBody byte[] requestBody) {
            return ResponseEntity.status(callRecording.service(hostedAccountId, mp3FileName, requestBody)).body(null);
        }
    

    它缺少@EnableWebMvc。我还更改了映射{mp3FileName:.+},因为它截断了请求的结尾,您可以查看SO问题here

    感谢@Selindek 的帮助

    【讨论】:

      猜你喜欢
      • 2016-04-19
      • 2021-01-01
      • 2019-05-04
      • 2020-05-19
      • 1970-01-01
      • 2020-04-21
      • 2011-09-12
      • 2015-04-02
      • 1970-01-01
      相关资源
      最近更新 更多