如何使用GlobalFilter在springcloud网关中设置响应值

时间:2018-06-27 13:14:50

标签: spring-cloud gateway

如何使用GlobalFilter在springcloud网关中设置响应值? 我不知道在ServerHttpResponse中使用哪种方法。

public class AuthGlobalFilterFilter1 implements GlobalFilter, Ordered {

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    Object key =  exchange.getRequest().getQueryParams().get("key");
    if(key==null){
        ServerHttpResponse serverHttpResponse =  exchange.getResponse();
        serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
        //in here,I want set the value of response body.such as json string "{"status":401}"
        return exchange.getResponse().setComplete();
    }
    return chain.filter(exchange);
}

1 个答案:

答案 0 :(得分:1)

我已经解决了。

        ServerHttpResponse serverHttpResponse = exchange.getResponse();
    serverHttpResponse.setStatusCode(HttpStatus.OK);
    byte[] response =  "{\"status\":\"erroe\",\"message\":\"error happen\"}".getBytes(StandardCharsets.UTF_8);;
    DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(response);
    return exchange.getResponse().writeWith(Flux.just(buffer));