解决springcloud的gateway中获取不到Post请求传入参数问题

解决gateway中获取不到post请求传入参数问题

由于最近的项目,用到了springboot+springcloud,需要在网关中做些参数的认证和限制,但是在开发中遇到获取不到post请求传入参数的问题,在网上搜索了半天也没能解决,最终还是靠着谷歌在外网搜索了半天最终解决了问题,希望这个帖子能够帮助跟我遇到同样问题的朋友。

造成这个问题的所在其实还是在于官方并不希望我们在网关中这样去操作,而是希望网关就做它应该做的事情。话不多说,直接上核心代码,第一次写帖子,请见谅。
@Component
public class ValidateFilter implements GlobalFilter, Ordered {

public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    System.out.println("-----------------全局过滤器MyGlobalFilter---------------------");
    System.out.println("-----------------请求方式---------------------");
	ServerRequest serverRequest = new DefaultServerRequest(exchange);
	// mediaType
	MediaType mediaType = exchange.getRequest().getHeaders().getContentType();
	String method = exchange.getRequest().getMethodValue();
    // read & modify body
    if ("POST".equals(method)) {

    Mono<String> modifiedBody = serverRequest.bodyToMono(String.class).flatMap(body -> {
        if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(mediaType)) {
            // origin body map
          //这是你post请求获取到的参数
            Map<String, Object> bodyMap = decodeBody(body);
              //这里做你的业务操作
             
                
            // new body map
            Map<String, Object> newBodyMap = new HashMap<>();
			//重新放回
            return Mono.just(encodeBody(newBodyMap));
        }
        return Mono.empty();
    });

	BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, String.class);
	HttpHeaders headers = new HttpHeaders();
	headers.putAll(exchange.getRequest().getHeaders());

	// the new content type will be computed by bodyInserter
	// and then set in the request decorator
	headers.remove(HttpHeaders.CONTENT_LENGTH);

	CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
	return bodyInserter.insert(outputMessage, new BodyInserterContext()).then(Mono.defer(() -> {
		ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(exchange.getRequest()) {

			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;
			}

			public Flux<DataBuffer> getBody() {
				return outputMessage.getBody();
			}
		};
		return chain.filter(exchange.mutate().request(decorator).build());
	}));
	}else if ("GET".equals(method)) {
        Map requestQueryParams = exchange.getRequest().getQueryParams();
        //TODO 得到Get请求的请求参数后,做你想做的事

        return chain.filter(exchange);
	}
    return chain.filter(exchange);
}


private Map<String, Object> decodeBody(String body) {
	return Arrays.stream(body.split("&")).map(s -> s.split("="))
			.collect(Collectors.toMap(arr -> arr[0], arr -> arr[1]));
}

private String encodeBody(Map<String, Object> map) {
	return map.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
}

@Override
public int getOrder() {
	return Ordered.HIGHEST_PRECEDENCE;
}

}

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐