java restTemplate请求get接口下载文件

java restTemplate请求get接口下载文件,第1张

restTemplate调用模块进行文件下载:

调用的方法是void方法,所以需要用restTemplate.exchange方法进行调用


调用过程:
  	被调用的目标接口:
    @GetMapping(value = "/fileDownload/{Id}")
    public void fileDownload(@PathVariable String Id
// 创建 RestTemplate 
 RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    // 调用下载接口进行下载
    // id 为String类型,为被调用接口参数
    ResponseEntity<byte[]> entity = restTemplate.exchange("被调用地址的url" + "/fileDownload/"+Id, HttpMethod.GET,new HttpEntity<>(headers), byte[].class);
    // 返回数据,在下面写到输出流里面
    byte[] body = entity.getBody();

 	try {
 			// 这三行是对文件名编码,与内容编码,可以不写
             fileName = FileNameUtils.fileNameEncoding(request, fileName);
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; " + fileName);
            // 把boby数据写入输出流输出
            response.getOutputStream().write(body);
        } catch (IOException e) {
            log.error("下载失败",e);
        }

总结:
	主要是restTemplate调用接口的时候一直报错,试了几种方法,这个成功解决了问题,所以记录下,
	要是有更好的方法可以评论说一下,一起多了解了解

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/790041.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-05
下一篇2022-05-05

发表评论

登录后才能评论

评论列表(0条)

    保存