zoukankan      html  css  js  c++  java
  • Zuul 修改请求体内容

    @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;
    }

  • 相关阅读:
    使用secureCRT连接VMware-Ubuntukylin虚拟机
    java使用POI jar包读写xls文件
    SimpleDateFormat 相关用法
    ORACLE之表
    ORACLE之PACKAGE-游标变量
    PHP多进程学习(三)__代码案例来了解父进程与子进程的执行顺序
    PHP多进程学习(二)__fork起多个子进程,父进程的阻塞与非阻塞
    PHP多进程学习(二)__来初步了解一下PHP多进程及简单demo
    Python学习【三】
    Python学习【二】
  • 原文地址:https://www.cnblogs.com/huoqm/p/14479108.html
Copyright © 2011-2022 走看看