gateway拦截器获取请求参数

package com.dp.config;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.CachedBodyOutputMessage;
import org.springframework.cloud.gateway.support.BodyInserterContext;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import javax.validation.constraints.NotNull;

/**
 * @author LLF
 * @title RequestBodyFilter
 * @date 2024/11/24 17:23
 * @description TODO
 */

@Component
public class RequestBodyFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().toString();
        HttpMethod method = request.getMethod();
        MediaType contentType = request.getHeaders().getContentType();
        if (HttpMethod.POST.equals(method)) {
            if (contentType != null && !contentType.toString().contains(MediaType.MULTIPART_FORM_DATA_VALUE)) {
                System.out.println("请求路径 {} 请求方法 {} 请求类型 {}"+uri+method.name()+ contentType);
                // ServerRequest serverRequest = new DefaultServerRequest(exchange);
                // 应该是版本问题,此版本的 DefaultServerRequest 类不是公共类,不能直接 new,需要改写下边的方式
                ServerRequest serverRequest = ServerRequest.create(exchange, HandlerStrategies.withDefaults().messageReaders());
                Mono<String> modifiedBody = serverRequest.bodyToMono(String.class)
                        .flatMap(body -> {
                            System.out.println("请求体 {}"+ body);
                            return Mono.just(body);
                        });
                BodyInserter<Mono<String>, ReactiveHttpOutputMessage> bodyInserter = BodyInserters.fromPublisher(modifiedBody, String.class);
                HttpHeaders headers = new HttpHeaders();
                headers.putAll(request.getHeaders());
                headers.remove(HttpHeaders.CONTENT_LENGTH);

                CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
                return bodyInserter.insert(outputMessage, new BodyInserterContext())
                        .then(Mono.defer(() -> {
                            ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(request) {
                                @NotNull
                                @Override
                                public HttpHeaders getHeaders() {
                                    long contentLength = headers.getContentLength();
                                    HttpHeaders httpHeaders = new HttpHeaders();
                                    httpHeaders.putAll(super.getHeaders());
                                    if (contentLength > 0) {
                                        httpHeaders.setContentLength(contentLength);
                                    } else {
                                        httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
                                    }
                                    return httpHeaders;
                                }

                                @NotNull
                                @Override
                                public Flux<DataBuffer> getBody() {
                                    return outputMessage.getBody();
                                }
                            };
                            return chain.filter(exchange.mutate().request(decorator).build());
                        }));
            } else {
                System.out.println("请求路径 {} 请求方法 {} 请求类型 {} 文件上传 不获取参数"+uri+method.name()+contentType);
            }
        }
        if (HttpMethod.GET.equals(method)) {
            String body = request.getQueryParams().toString();
            System.out.println("请求路径 {} 请求方法 {} 请求类型 {} 请求参数 {}"+","+uri+","+method.name()+","+contentType+","+body);
            return chain.filter(exchange);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }

}

 

posted @ 2024-11-24 17:34  _Lawrence  阅读(2)  评论(0编辑  收藏  举报