GateWay 修改请求内容(post)

2023-03-01 17:11:29 浏览数 (1)

1、自定义网关过滤器实现 GlobalFilter, Ordered

代码语言:javascript复制
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        对阿里网关添加参数统一处理

        if (HttpMethod.POST.matches(method)) {
            return DataBufferUtils.join(request.getBody()).flatMap(dataBuffer -> {
//                读取
                CharBuffer charBuffer = StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer());
//                释放
                DataBufferUtils.release(dataBuffer);
                //进行想要的处理即可
                return chain.filter(exchange.mutate().request(createServerHttpRequest(request, queryParam.getUri(), object)).build());
            });
        } else if (HttpMethod.GET.matches(method)) {
//            重写参数
            return chain.filter(exchange.mutate().request(request.mutate().uri(queryParam.getUri()).build()).build());
        }
        return chain.filter(exchange);
    }

2、注意点

代码语言:javascript复制
ServerHttpRequest request = exchange.getRequest();
exchange.getRequest().getBody()

在读取body内容时不要使用exchange.getRequest().getBody().subscribe()去实现,可能本人比较菜不知道具体使用方法,如果有人指出请评论

修改完body进行回写时,注意时修改header 的 ContentLength ,修改body之后http协议 ContentLength 会有变化最好重新写入新的body对应字节长度

代码语言:javascript复制
newRequest = new ServerHttpRequestDecorator(newRequest) {
    @NonNull
    @Override
    public Flux<DataBuffer> getBody() {
        return Flux.defer(() -> Mono.just(bodyDataBuffer));
    }

    @NonNull
    @Override
    public HttpHeaders getHeaders() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.putAll(super.getHeaders());
        if (bodyDataBuffer.capacity() > 0) {
            httpHeaders.setContentLength(bodyDataBuffer.capacity());
        } else {
            // TODO: this causes a 'HTTP/1.1 411 Length Required' on httpbin.org
            httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
        }
        return httpHeaders;
    }
};

0 人点赞