【问题标题】:Sending a multipart request using RestTemplate使用 RestTemplate 发送多部分请求
【发布时间】:2020-01-03 03:28:27
【问题描述】:

我想向一些外部 API(使用 Spring Boot 创建)发出多部分请求,但我得到的只是Required request part 'file' is not present

我知道外部 API 的源代码,但无法修改。它看起来像这样:

    @PostMapping("/upload")
    public ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file){
        return ResponseEntity.ok().build();
    }

从我的应用程序中,我创建和发送请求与以下 sn-p 完全相同:

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> body
                = new LinkedMultiValueMap<>();
        body.add("file", "dupa".getBytes());

        HttpEntity<MultiValueMap<String, Object>> requestEntity
                = new HttpEntity<>(body, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate
                .postForEntity("http://api:8080/upload", requestEntity, String.class);
        return response.getBody();

它不起作用的原因是什么?上面使用 Apache HttpClient 重写的代码就像魅力一样。

【问题讨论】:

  • 据我所知,你的MultiValueMap中“文件”值的数据类型应该是FileSystemResource

标签: spring spring-boot resttemplate


【解决方案1】:

你基本上有两种选择,字节数组的解决方案:

    map.add("file", new ByteArrayResource(byteArrayContent) {
        @Override
        public String getFilename() {
            return "yourFilename";
        }
    });

我记得只添加一个字节数组有问题,所以你也需要一个文件名并使用 ByteArrayResource。

或者添加一个文件:

    map.add("file", new FileSystemResource(file));

【讨论】:

  • 嗯,这就解释了 HttpClient 工作的原因。它在其构造函数之一中具有文件名字段。我想知道为什么没有人在互联网上正确解释它。谢谢
猜你喜欢
  • 2011-05-06
  • 2020-09-24
  • 1970-01-01
  • 1970-01-01
  • 2014-05-19
  • 2018-01-06
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多