简体   繁体   中英

Remove Content-Length and Transfer-Encoding Headers from spring servlet HTTP Response

I want to know if there is a way of removing those headers from my current response. I am using the @ResponseBody annotation and already have tried using a Filter to try to not add those headers, based on the following How do delete a HTTP response header? .

Ideally, the HTTP response should be like the one from this link: https://api.github.com/users/mralexgray/repos with no Content-Length and Transfer-Encoding headers.

You could write directly to the HttpServletResponse's OutputStream. Spring will give you the HttpServletResponse (and the HttpServletRequest) if you want it, simply by adding it to your method signature.

This way you have (mostly) full control of headers. You would probably need to create the JSON yourself, but it's usually quite simple. For example...

private ObjectMapper mapper = new ObjectMapper();

@RequestMapping(value = "/getStuff", method = RequestMethod.GET)
public void getStuff(HttpServletResponse httpServletResponse) throws Exception {
    try {
        httpServletResponse.setHeader("Pragma","public");
        httpServletResponse.setHeader("Expires","0");
        httpServletResponse.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
        httpServletResponse.setHeader("Cache-Control","public");
        OutputStream outputStream = httpServletResponse.getOutputStream();
        try {
            mapper.writeValue(outputStream, myObject);
        } finally {
            outputStream.close();
        }

This might not seem elegant, but by using @ResponseBody you are using that as a convenience to do all the hard work in creating the response. But if it is not creating the response as you would like it, you can take a step back and do it "manually" using HttpServletResponse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM