Zuul代理添加参数以请求网址

时间:2016-10-31 13:07:32

标签: spring-boot httprequest netflix-zuul

我使用ZuulFilter来拦截请求调用。我需要通过添加这样的附加参数来更改请求调用的URL。

原始请求

Http://localhost:8080/home?username=Paul
添加新参数

Http://localhost:8080/home?username=Paul&authenticated=true

我不需要将此附加参数添加到标头中。我尝试使用setRequestQueryParams将新参数添加到请求网址,但它没有用。

你能告诉我如何使用zuul代理向url添加新参数吗?

2 个答案:

答案 0 :(得分:1)

您也可以使用ZuulFilter。创建ZuulFilter类:

public class AuthenticatedFilter extends ZuulFilter{

  @Override
  public String filterType() {
    return "pre";
  }

  @Override
  public int filterOrder() {
    return 10;
  }

  @Override
  public boolean shouldFilter() {
    return true;
  }

  @Override
  public Object run() {
    RequestContext context = RequestContext.getCurrentContext();
    Map<String, List<String>> newParameterMap = new HashMap<>();
    Map<String, String[]> parameterMap = context.getRequest().getParameterMap();
    //getting the current parameter
    for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
      String key = entry.getKey();
      String[] values = entry.getValue();
      newParameterMap.put(key, Arrays.asList(values));
    }
    //add a new parameter
    String authenticatedKey = "authenticated";
    String authenticatedValue = "true";
    newParameterMap.put(authenticatedKey,Arrays.asList(authenticatedValue));
    context.setRequestQueryParams(newParameterMap);
    return null;
  }
}

在你的@SpringBootApplication中将过滤器添加为bean

  @Bean
  public AuthenticatedFilter authenticatedFilter() {
    return new AuthenticatedFilter();
  }

答案 1 :(得分:0)

创建过滤器。

public class SimpleCORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        Map<String, String[]> qp = new HashMap<String, String[]>();
        for(String key : request.getParameterMap().keySet()){
            qp.put(key, new String[]{request.getParameterMap().get(key)[0]});
        }
        ......
        qp.put("authenticated", new String[]{""});
        chain.doFilter(new PrettyFacesWrappedRequest(request, qp), resp);
    }

    @Override
    public void destroy() {}
}

IN Application.java

@Bean
public SimpleCORSFilter simpleCORSFilter(){
    return new SimpleCORSFilter();
}