gpt4 book ai didi

java - 从 ServerHttpRequest/Flux 获取请求体字符串

转载 作者:行者123 更新时间:2023-11-30 12:03:39 30 4
gpt4 key购买 nike

我正在使用 spring boot 版本 - 2.0.6.RELEASE 和 spring cloud 版本 - Finchley.SR2

并且我已经创建了我的自定义网关过滤器来修改请求正文。

但是在使用 Flux 将请求正文转换为字符串时,我得到一个空字符串。我需要一种方法来获取与我的请求正文相对应的字符串。

@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = (ServerHttpRequest) exchange.getRequest();
String s = resolveBodyFromRequest(request);
/* s comes out to be "" */
return chain.filter(newExchange);


}



private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest){
//Get the request body
Flux<DataBuffer> body = serverHttpRequest.getBody();
StringBuilder sb = new StringBuilder();

body.subscribe(buffer -> {
byte[] bytes = new byte[buffer.readableByteCount()];
buffer.read(bytes);
DataBufferUtils.release(buffer);
String bodyString = new String(bytes, StandardCharsets.UTF_8);
sb.append(bodyString);
});
return sb.toString();

}

最佳答案

您可以使用 ModifyRequestBodyGatewayFilterFactory我相信它包含在 Spring Cloud Gateway 2.0.2 中,它是 Finchley 的一部分.

例如:

@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
ModifyRequestBodyGatewayFilterFactory.Config modifyRequestConfig = new ModifyRequestBodyGatewayFilterFactory.Config()
.setContentType(ContentType.APPLICATION_JSON.getMimeType())
.setRewriteFunction(String.class, String.class, (exchange1, originalRequestBody) -> {
String modifiedRequestBody = yourMethodToModifyRequestBody(originalRequestBody);
return Mono.just(modifiedRequestBody);
});

return new ModifyRequestBodyGatewayFilterFactory().apply(modifyRequestConfig).filter(exchange, chain);
};
}

关于java - 从 ServerHttpRequest/Flux<DataBuffer> 获取请求体字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57562873/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com