如何在Spring Cloud Gateway中获取请求标头值

时间:2018-07-10 13:12:58

标签: spring-boot spring-cloud-gateway

我正在使用Spring Cloud Gateway实现API路由,在一种用例中,我需要从传入请求中获取标头值并将其用于某些处理,然后将此处理后的值进一步添加到传出(路由的)API调用中作为标头。如何从routeBuilder中的传入API调用中获取标头值?

    from BeautifulSoup import BeautifulSoup

    import urllib2 
    url = urllib2.urlopen("https://www.python.org")

    content = url.read()

    soup = BeautifulSoup(content)

    title = soup.findAll("title")

    paragraphs = soup.findAll("p")

    print paragraphs[1] //Second paragraph with tags

    print paragraphs[1].text //Second paragraph without tags

2 个答案:

答案 0 :(得分:0)

您可以为此编写一个自定义过滤器。它只是一种解决方法,不确定执行此操作的最佳方法是什么:

public class SomeFilterFactory
        extends AbstractGatewayFilterFactory<SomeFilterFactory.SomeConfig> {



    public SomeFilterFactory() {
        super(SomeFilterFactory.SomeConfig.class);
    }

    @Override
    public GatewayFilter apply(SomeFilterFactory.SomeConfig config) {

        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String someHeader = request.getHeaders().getFirst("someHeader");
            // do your things here
            return chain.filter(exchange);
        };
    }

    public static class SomeConfig {
        // your config if required
        // or use name value config

    }

}

答案 1 :(得分:0)

从谓词获取传入的请求/响应。

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes().route("default-api-route", new Function<PredicateSpec, Route.AsyncBuilder>() {
        @Override
        public Route.AsyncBuilder apply(PredicateSpec predicateSpec) {
            return predicateSpec.predicate(new Predicate<ServerWebExchange>() {
                @Override
                public boolean test(ServerWebExchange serverWebExchange) {
                    // get request header here
                    return false;
                }
            }).uri("http://httpbin.org").order(10000);
        }
    }).build();
}