【发布时间】:2021-10-14 21:05:58
【问题描述】:
我有一个 GatewayFilter。它接收一个请求,
- 首先检查签名(代码省略)
- 查询一些需要的参数
- 将它们添加到请求中
- 最终转发请求
如何将查询参数作为 json 添加到请求正文中?
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpResponse response = exchange.getResponse();
ServerHttpRequest request = exchange.getRequest();
BodyInserter<Mono<String>, ReactiveHttpOutputMessage> bodyInserter = getBodyInsert(exchange);
CachedBodyOutputMessage outputMessage = getCachedBodyOutputMessage(exchange);
return bodyInserter.insert(outputMessage, new BodyInserterContext()).then(Mono.defer(() -> {
//1.checks the signature (omit)
//2. get these parameters remotely
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("calcPackageId", 10000);
paramMap.put("userId", 10001);
paramMap.put("barId", 10002);
String body = JSON.toJSON(paramMap);
//3. todo how to set request body {"calcPackageId":"10000","barId":"10002","userId":"10001"} ??????
//4 forwards the request
return chain.filter(exchange.mutate().request(newRequest).build());
}));
}
//not important
private BodyInserter<Mono<String>, ReactiveHttpOutputMessage> getBodyInsert(ServerWebExchange exchange) {
ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
Mono<String> rawBody = serverRequest.bodyToMono(String.class).map(s -> s);
return BodyInserters.fromPublisher(rawBody, String.class);
}
private CachedBodyOutputMessage getCachedBodyOutputMessage(ServerWebExchange exchange) {
HttpHeaders tempHeaders = new HttpHeaders();
tempHeaders.putAll(exchange.getRequest().getHeaders());
tempHeaders.remove(HttpHeaders.CONTENT_LENGTH);
return new CachedBodyOutputMessage(exchange, tempHeaders);
}
【问题讨论】:
标签: java spring-boot spring-cloud spring-cloud-gateway