首页 > 解决方案 > 如何使用feign客户端实现下载文件

问题描述

我有一个下载文件的网址。url 的签名是http://services.local/api/v1/downloadFile?messageId=11090。我想使用 feign 客户端代理它。每次我得到一个异常,告诉我的输出流已关闭。

Fri Nov 02 16:18:47 IST 2018 出现意外错误(类型=内部服务器错误,状态=500)。无法写入 JSON:已为此响应调用 getOutputStream();嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: getOutputStream() 已经为此响应调用(通过参考链:org.springframework.security.web.firewall.FirewalledResponse["response"]->org.springframework. security.web.header.HeaderWriterFilter$HeaderWriterResponse["response"]->org.springframework.security.web.context.HttpSessionSecurityContextRepository$SaveToSessionResponseWrapper["response"]->org.springframework.security.web.firewall.FirewalledResponse["response "]->org.apache.catalina.connector.ResponseFacade["writer"])

我的假客户端很简单

 @FeignClient(name = "downloadAPI", url = "${service.ip}")
public interface DownloadApiProxy {

    @RequestMapping(method = RequestMethod.GET, value = "/downloadFile")
    public void downloadFile(HttpServletResponse response,
            @RequestParam(value = "downloadMessageId", required = false) String messageId);

标签: javaspringspring-cloudspring-cloud-feign

解决方案


我遇到了同样的问题,我想从一个微服务到另一个微服务进行 API 调用,所以我映射了返回的 API byte[]

所以你的代码应该是这样的:

@FeignClient(name = "downloadAPI", url = "${service.ip}")
public interface DownloadApiProxy {

    @RequestMapping(method = RequestMethod.GET, value = "/downloadFile")
    public byte[] downloadFile(HttpServletResponse response, @RequestParam(value = "messageId", required = false) String messageId);

     :
     :
}

它将返回下载的文件byte[]

注意:您的查询参数将messageId与给出的示例相同。


推荐阅读