一、问题背景:
开发中有时候有的功能需要返回content-length字段,根据此字段进行下载进度的展示。而springboot默认在数据量大的时候是进行了Transfer-Encoding: chunked
设置的。
需要我们手动对需要返回Content-Length: 574712
的接口进行filter配置。
二、添加filters
FilterConfig.java
package com.eduer.books.config;
import com.eduer.books.modules.app.filters.AddContentLengthFilter;
import com.google.common.collect.Lists;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* Filter配置
*
* @author books
*/
@Configuration
public class FilterConfig {
/**
* 给特定接口加content-length返回
* @return FilterRegistrationBean
*/
@Bean
public FilterRegistrationBean contentLengthFilterRegistrationBean() {
FilterRegistrationBean filterBean = new FilterRegistrationBean();
filterBean.setFilter(new AddContentLengthFilter());
List<String> urls = Lists.newArrayList();
// 只针对指定接口类型返回content-length
urls.add("/app/clientApi");
filterBean.setUrlPatterns(urls);
return filterBean;
}
}
三、新建AddContentLengthFilter
AddContentLengthFilter.java
package com.eduer.books.modules.app.filters;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingResponseWrapper;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AddContentLengthFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
ContentCachingResponseWrapper cacheResponseWrapper;
if (!(response instanceof ContentCachingResponseWrapper)) {
cacheResponseWrapper = new ContentCachingResponseWrapper(response);
} else {
cacheResponseWrapper = (ContentCachingResponseWrapper) response;
}
filterChain.doFilter(request, cacheResponseWrapper);
cacheResponseWrapper.copyBodyToResponse();
}
}
四、测试:
4.1 修改前:
Response Headers没有返回 Content-Length: 574712
的属性。
4.2 修改后:
已经成功添加了 Content-Length: 574712
的属性。
END
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)