如何从http标头中提取参数“ session-id”,并将其写入响应中?
webClient.post()
.uri(host)
.syncBody(req)
.retrieve()
.bodyToMono(MyResponse.class)
.doOnNext(rsp -> {
//TODO how can I access clientResponse.httpHeaders().get("session-id") here?
rsp.setHttpHeaderSessionId(sessionId);
})
.block();
class MyResponse {
private String httpHeaderSessionId;
}
答案 0 :(得分:1)
您不需要使用exchange
函数,而不必使用retrieve
webClient.post()
.uri(host)
.syncBody(req)
.exchange()
.flatMap(response -> {
return response.bodyToMono(MyResponse.class).map(myResponse -> {
List<String> headers = response.headers().header("session-id");
// here you build your new object with the response
// and your header and return it.
return new MyNewObject(myResponse, headers);
})
});
}).block();
class MyResponse {
// object that maps the response
}
class MyNewObject {
// new object that has the header and the
// response or however you want to build it.
private String httpHeaderSessionId;
private MyResponse myResponse;
}
或带有可变对象:
...
.exchange()
.flatMap(rsp -> {
String id = rsp.headers().asHttpHeaders().getFirst("session-id");
return rsp.bodyToMono(MyResponse.class)
.doOnNext(next -> rsp.setHttpHeaderSessionId(id));
})
.block();