ZuulFilter總結

zuulFilter使用總結

pre:可以在請求被路由之前調用
route:在路由請求時候被調用
post:在route和error過濾器之後被調用
error:處理請求時發生錯誤時被調用

一、攔截request請求,對請求進行修改(pre/route)
1.修改url地址

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request
        String uri = request.getRequestURI();
        LOG.info("=======old uri: "+uri);
        uri += "";
        ctx.put(FilterConstants.REQUEST_URI_KEY, uri);
        LOG.info("=======new uri: "+ctx.getRequest().getRequestURI());

2.修改get請求參數

        RequestContext ctx = RequestContext.getCurrentContext();
        Map<String, List<String>> requestQueryParams = ctx.getRequestQueryParams();
        if (requestQueryParams==null) {
            requestQueryParams=new HashMap<>();
        }
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("value");
        requestQueryParams.put("key", arrayList);
        ctx.setRequestQueryParams(requestQueryParams);

3.修改post請求參數

        try{
            ServletInputStream inputStream = ctx.getRequest().getInputStream();
            String params = StreamUtils.copyToString(inputStream, Charset.forName("UTF-8"));
            LOG.info("======原先參數爲: "+params);
            JsonObject jsonObject = new JsonParser().parse(params).getAsJsonObject();
            jsonObject.addProperty("key","value");
            String newParam = new Gson().toJson(jsonObject).toString();
            ctx.setRequest(new HttpServletRequestWrapper(ctx.getRequest()) {
                @Override
                public ServletInputStream getInputStream(){
                    return new ServletInputStreamWrapper(newParam.getBytes());
                }
                @Override
                public int getContentLength() {
                    return newParam.getBytes().length;
                }
                @Override
                public long getContentLengthLong() {
                    return newParam.getBytes().length;
                }
            });
            LOG.info("======修改後的參數爲: "+StreamUtils.copyToString(ctx.getRequest().getInputStream(), Charset.forName("UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
        }

二、攔截response請求,修改響應參數(post)

    try {
        InputStream stream = ctx.getResponseDataStream();
        String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
        JsonObject resObject = new JsonParser().parse(body).getAsJsonObject();
        if(resObject.has("error")){
            resObject.addProperty("code",-1);
        }else{
            resObject.addProperty("code",1);
        }
        String newBody = resObject.toString();
        ctx.setResponseBody(newBody);
        LOG.info("====返回結果:"+ctx.getResponseBody());
    }catch (Exception e){
        e.printStackTrace();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章