gpt4 book ai didi

java - 如何在WebClient响应中提取http header ?

转载 作者:行者123 更新时间:2023-12-02 09:42:25 25 4
gpt4 key购买 nike

如何从http header 中提取参数“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;
}

最佳答案

不可能使用检索。您需要使用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;
}

Webclient Exchange

或者使用可变对象:

...
.exchange()
.flatMap(rsp -> {
String id = rsp.headers().asHttpHeaders().getFirst("session-id");
return rsp.bodyToMono(MyResponse.class)
.doOnNext(next -> rsp.setHttpHeaderSessionId(id));
})
.block();

关于java - 如何在WebClient响应中提取http header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969580/

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