RestTemplate发送http请求并上传文件流

最近项目种遇到一个场景,再调用http接口的时候,请求体需要用文件流,当时百度了很多帖子,发现基本全都是以下这种方法:

    private InputStream convertPdf(MultipartFile multipartFile) throws IOException {
        File file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
        FileSystemResource resource = new FileSystemResource(file);
        MultiValueMap<String, Object> params = new LinkedMultiValueMap();
        params.add("file", resource);
        params.add("dstFormat", "pdf");
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Resource> entity = restTemplate.postForEntity(convertPdfUrl, params, Resource.class);
        InputStream ins = Objects.requireNonNull(entity.getBody()).getInputStream();
        return ins;
    }

搜了很多发现千篇一律是这种,但是我目前的需求场景需要脱离File,直接使用流,因为我的输入流是从ftp服务器所获取的,于是自己尝试用byte[]作为实体,发现成功有效:

    public void handEvent(String fileName) {
        try {
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            InputStream inputStream = null;
             //下载文件
            inputStream  = ftpUtil.downloadFIle(fileName);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int temp;
            while ((temp = inputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, temp);
            }
            //文件流转byte[]
            byte[] by = byteArrayOutputStream.toByteArray();
            String url = "http://xxxxx";
            HttpEntity<byte[]> httpEntity = new HttpEntity<>(by, headers);
            HttpEntity<String> result = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);
            log.info("--------上传结果:{}", result);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
您可以使用`RestTemplate`发送带有文件的POST请求。以下是一个示例: ```java import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.io.File; public class FileUploadExample { public static void main(String[] args) { String url = "http://example.com/upload"; String filePath = "/path/to/file.txt"; RestTemplate restTemplate = new RestTemplate(); // 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); // 构建请求体 MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add("file", new FileSystemResource(new File(filePath))); // 构建请求实体 HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers); // 发送请求 ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class); // 处理响应 if (response.getStatusCode().is2xxSuccessful()) { System.out.println("文件上传成功"); } else { System.out.println("文件上传失败"); } } } ``` 在上述示例中,您需要设置正确的URL和文件路径。通过将文件包装在`FileSystemResource`中,并将其添加到`MultiValueMap`中,您可以将文件作为Multipart形式的请求体发送到服务器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值