使用RestTemplate请求远程接口上传文件

使用 RestTemplate 请求接口下载文件: https://blog.csdn.net/weixin_44953227/article/details/124683295

上传代码

如果是本地文件可以使用这个方法

FileSystemResource resource = new FileSystemResource("文件路径");

@RestController
@RequestMapping("/test")
public class TestUploadController {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
    private RestTemplate restTemplate;

    @PostMapping("/upload")
    public Object getGdDzyzApiService(@RequestParam("file") MultipartFile file) {
        Resource resource = file.getResource();
        // 获取本地文件资源
        // FileSystemResource resource = new FileSystemResource("home/java/test.pdf");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        // 设置文件
        param.add("file", resource);
        HttpEntity<MultiValueMap> httpEntity = new HttpEntity<>(param, httpHeaders);

        String url = "https://blog.csdn.net/upload/file";
        logger.info(">>> 上传文件url: {}", url);

        try {
            URI uri = new URI(url);

            ResponseEntity<Map> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, Map.class);
            logger.warn(">>> responseEntity: {}", responseEntity);

            if (responseEntity.getStatusCodeValue() != HttpStatus.OK.value()) {
                logger.error(">>> 状态码异常: {}", responseEntity.getStatusCodeValue());
                throw new RuntimeException(String.format("状态码异常 %s", responseEntity.getStatusCodeValue()));
            }
            
            Map body = responseEntity.getBody();
            if (body == null) {
                throw BusinessException.withErrorMsg("返回结果为空");
            }

            return body;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "上传失败";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值