从spring servlet HTTP响应中删除Content-Length和Transfer-Encoding标头 [英] Remove Content-Length and Transfer-Encoding Headers from spring servlet HTTP Response

查看:361
本文介绍了从spring servlet HTTP响应中删除Content-Length和Transfer-Encoding标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以从当前响应中删除这些标头.我正在使用@ResponseBody批注,并且已经尝试根据以下

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?.

理想情况下,HTTP响应应类似于此链接中的响应: https://api .github.com/users/mralexgray/repos 没有Content-Length和Transfer-Encoding标头.

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.

推荐答案

您可以直接写入HttpServletResponse的OutputStream.如果愿意,Spring会给您HttpServletResponse(和HttpServletRequest),只需将其添加到方法签名中即可.

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.

这样,您可以(大部分)完全控制标题.您可能需要自己创建JSON,但这通常很简单.例如...

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();
        }

这似乎不太优雅,但是通过使用@ResponseBody,您可以方便地完成创建响应的所有艰苦工作.但是,如果它没有按照您的意愿创建响应,则可以退后一步,然后使用HttpServletResponse手动"完成该操作.

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.

这篇关于从spring servlet HTTP响应中删除Content-Length和Transfer-Encoding标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆