如何使用feign客户端实现下载文件

How to implement a download file using feign client

我有一个 url 可以下载文件。 url 的签名是 http://services.local/api/v1/downloadFile?messageId=11090.I 想使用 feign 代理它 client.Every 时我得到一个异常告诉我的输出流已关闭。

Fri Nov 02 16:18:47 IST 2018 There was an unexpected error (type=Internal Server Error, status=500). Could not write JSON: getOutputStream() has already been called for this response; nested exception is com.fasterxml.jackson.databind.JsonMappingException: getOutputStream() has already been called for this response (through reference chain: 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"])

我的feign客户端很简单

 @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);

我遇到了同样的问题,我想从一个微服务调用 API 到另一个微服务,所以我将 API 映射到 returning 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);

     :
     :
}

它将 return 下载文件 byte[]

注意:您的查询参数将是 messageId 作为给定示例。