【FeignClient】feignClient跨服务下载文件

背景:服务端提供了一个下载服务,用FeignClient调用该服务时发生错误。
错误信息为:getOutputStream() has already been called for this response
此错误原因是response已经被调用
解决方法:需要用到Feign提供的Request来做一次中继操作

代码:

服务端:

    /**
     * 下载文件
     * @param filePath  文件路径
     * @param downloadName  下载后的文件名(1.txt)
     * @param response
     */
    public static void downloadFile(String filePath, String downloadName, HttpServletResponse response) throws UnsupportedEncodingException {
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((downloadName).getBytes(), "iso-8859-1"));
        response.setContentType("text/plain;charset=utf-8");
        File file = new File(filePath);
        InputStream in = null;
        if(file.exists()){
            try {
                OutputStream out = response.getOutputStream();
                in = new FileInputStream(file);
                byte buffer[] = new byte[1024];
                int length = 0;
                while ((length = in.read(buffer)) >= 0){
                    out.write(buffer,0,length);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(in != null){
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


    }
    @GetMapping("download")
    public void downloadYjya(HttpServletResponse response) throws IOException {
        downloadFile(?, ?, response);
    }

客户端:

public interface RtYjClient {

  @GetMapping("download")
  Response downloadYjya();

}
  @GetMapping("download")
  public void downloadYjya(HttpServletResponse servletResponse) throws IOException {
    Response response = rtYjClient.downloadYjya();
    Response.Body body = response.body();
    for (Object key : response.headers().keySet()) {
      List<String> kList = (List<String>) response.headers().get(key);
      for (String val : kList) {
        servletResponse.setHeader(key.toString(), val);
      }
    }
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
      inputStream = body.asInputStream();
      outputStream = servletResponse.getOutputStream();
      byte[] b = new byte[inputStream.available()];
      inputStream.read(b);
      outputStream.write(b);
      outputStream.flush();
    } catch (IOException e) {
      System.out.println("失败了");
    }finally {
      inputStream.close();
      outputStream.close();
    }
  }

参考文章:

1,https://www.jb51.net/article/160275.htm

2,FeignClient 跨服务上传文件、导出Excel_赵丙双的博客-CSDN博客_feign 导出excel

3,Feign跨服务下载文件; getOutputStream() has already been called for this response_在你之后的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/u013517229/article/details/124326943