Spring Boot + Zuul: how to get the "Content-length" header from a file stream provided by RESTful services?

5.4k views Asked by At

I am using Spring Cloud and Zuul proxy as gateway to my RESTful service provided by a microservice. When I perform a request directly to an instance of a microservice, all the headers are provided as I expected. However, when the same request is proxied by Zuul, the header "Content-length" is removed. I've made some research about it and I saw that Zuul adds the header "Transfer-Encoding" as "chunked" and in this case the header Content-length is omitted (Content-Length is being stripped, Spring Cloud Netflix: Whats happening in ZuulConfiguration with the ZuulServlet?).

However, I really need to get the "Content-length" provided by my RESTful service. This request also must be proxied by Zuul (I have many instances of a microservice, so I wouldn't access them directly).

Here is the method in my microservice:

@RequestMapping(value = "/jobresult/{id}", method = RequestMethod.GET)
@Timed
public ResponseEntity<InputStreamResource> downloadJobResult(@PathVariable Long id) {
    Job job = jobService.findOne(id);
    File file = new File(job.getTargetFile());
    try {
       return ResponseEntity.ok().contentLength(file.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(new InputStreamResource(new FileInputStream(file)));
    } catch (FileNotFoundException e) {
       log.error(e.getMessage(), e);
    }
}

For example, the request to /api/jobresult/1 provides the header "Content-length" correctly, but the request to /service/api/jobresult/1 (routed by Zuul) do not show this header and also modify the "Transfer-Encoding" to "chunked".

2

There are 2 answers

1
Emil On BEST ANSWER

The response filter for Zuul from Spring Cloud Netflix code is causing the issue.

Solution

Add an application.properties file in your src/main/resources if you don't have it and add the following line:

zuul.set-content-length=true
0
Diego Pessoa On

Unfortunately I couldn't find a answer for this problem. To make the things work, I wrote an alternative header "X-Content-Length" containing the file size.

In this way, Zuul does not erase the header and I can read it in the client side. As I have the control of both, it is not a problem. But in other cases, the clients should be aware of such header.