Zuul 修改請求體內容
阿新 • • 發佈:2018-11-03
- 樣例程式碼:
/** * @Author:大漠知秋 * @Description:修改請求體內容 * @CreateDate:4:35 PM 2018/10/31 */ @Component @Slf4j public class ModifyRequestEntityFilter extends ZuulFilter { @Override public String filterType() { return PRE_TYPE; } @Override public int filterOrder() { return PRE_DECORATION_FILTER_ORDER + 1; } @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); try { // 編碼格式 String charset = ctx.getRequest().getCharacterEncoding(); InputStream in = (InputStream) ctx.get("requestEntity"); if (null == in) { in = ctx.getRequest().getInputStream(); } String requestEntityStr = StreamUtils.copyToString(in, Charset.forName(charset)); requestEntityStr = URLDecoder.decode(requestEntityStr, charset); JSONObject requestEntityJson = JSONObject.parseObject(requestEntityStr); // 新增引數 requestEntityJson.put("newParam", "1111111"); byte[] requestEntityBytes = requestEntityJson.toJSONString().getBytes(charset); ctx.setRequest(new HttpServletRequestWrapper(ctx.getRequest()) { @Override public ServletInputStream getInputStream() throws IOException { return new ServletInputStreamWrapper(requestEntityBytes); } @Override public int getContentLength() { return requestEntityBytes.length; } @Override public long getContentLengthLong() { return requestEntityBytes.length; } }); } catch (Exception e) { // 用來給後面的 Filter 標識,是否繼續執行 ctx.set(SessionContants.LOGIC_IS_SUCCESS, false); // 返回資訊 ctx.setResponseBody(String.format(SessionContants.ERROR_RESPONSE_BODY, "修改請求體出錯")); // 對該請求禁止路由,禁止訪問下游服務 ctx.setSendZuulResponse(false); log.error("【修改請求體 Filter】-出錯了:{}", ExceptionUtils.getStackFrames(e)); } return null; } }