当前位置:   article > 正文

java 调用第三方接口返回文件流并下载文件_java调用第三方接口下载文件

java调用第三方接口下载文件
@PostMapping("/file/download")
    public AjaxResult downFileById(@RequestBody FileInput input,HttpServletResponse response) throws IOException {
        String creditCode = input.getCreditCode();
        //生成 sso
        String sso = createSso(creditCode);
        Long fileId = input.getFileId();
        Map<String,Object> requestParam = new HashMap<>();
        // 设置请求参数
        requestParam.put("sso",sso);
        requestParam.put("id",fileId);
        // 调用第三方接口
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity request = new HttpEntity(requestParam, headers);
        //当接受一个文件流时必须使用 resource (spring)接收
        ResponseEntity<Resource> entity = restTemplate.postForEntity(FILEURL, request,Resource.class);
        InputStream in = entity.getBody().getInputStream();
        //调用下载文件接口
        FileUtils fileUtils = new FileUtils();
        fileUtils.downloadFile(response,in,"123.doc");
        return AjaxResult.success();
    }




public AjaxResult downloadFile(HttpServletResponse response, InputStream inputStream, String filename) {
        filename = UriUtils.encode(filename, "UTF-8");
        response.setContentType("multipart/form-data;");
        response.setContentType("application/force-download");
        //设置下载的文件名
        response.addHeader("Content-Disposition", "attachment;fileName*=UTF-8''" + filename);
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(inputStream);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            return AjaxResult.error();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }

        return null;
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/207101
推荐阅读
相关标签
  

闽ICP备14008679号