request中統一對header中的物件值進行處理
阿新 • • 發佈:2019-01-04
主要利用
javax.servlet.http.HttpServletRequestWrapper進行包裝
package com.pica.cloud.foundation.utils.utils; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.io.BufferedReader; importjava.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.*; /** * @param * @author liugen.wen sixvision * @version V1.0 1、request克隆 2、提供增加header裡面放置物件的方法 * @ClassName: * @Description: * @date 2018/6/26 14:03 */ public classBodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper { private final byte[] body; private Map<String,String> headerMap; public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException { super(request); // 提取原本的HEADER內容 Enumeration enumeration = request.getHeaderNames(); headerMap= new HashMap<String,String>(); while(enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); headerMap.put(name, request.getHeader(name)); } body = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8")); } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() throws IOException { final ByteArrayInputStream bais = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() throws IOException { return bais.read(); } @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener readListener) { } }; } public void addHeader(String name,String value) { headerMap.put(name, value); } @Override public String getHeader(String name) { return headerMap.get(name); } @Override public Enumeration getHeaderNames() { Set<String> set = new HashSet<String>(headerMap.keySet()); Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames(); while (e.hasMoreElements()) { String n = e.nextElement(); set.add(n); } // create an enumeration from the set and return return Collections.enumeration(set); } public Map getHeaderMap() { return headerMap; } public void setHeaderMap(Map headerMap) { this.headerMap = headerMap; } }
在使用的時候(建議在Filter中) 就先new 再直接 addHeader 再把物件傳遞下去
BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(req);
requestWrapper.addHeader("picaUser", URLEncoder.encode(JSONObject.toJSONString(picaUser), "UTF-8"));
chain.doFilter(requestWrapper, resp);