Search code examples
javaspring-bootnetflix-eurekanetflix-zuul

How to find the content-length of Page <Entity> to be passed as the http header?


I am using spring boot along with Netflix Eureka. I need to find the total length of Page to set the content-length in the HTTP response header. My controller is like this ...

Page<exampleEntity> examplePage = null;
examplePage=exampleService.getFuntion(request, params);
HttpHeaders headers = new HttpHeaders();
headers.setContentLength(???);
return new ResponseEntity<>(Page, HttpHeaders ,HttpStatus.OK);

...

could anyone please help?


Solution

  • ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream out = null;
    try {
      out = new ObjectOutputStream(bos);   
      out.writeObject(yourObject);
      out.flush();
      byte[] yourBytes = bos.toByteArray();
      
    } finally {
      try {
        bos.close();
      } catch (IOException ex) {
        // ignore close exception
      }
    }
    

    Then yourBytes.length is what you need