简体   繁体   English

如何在 WebClient 响应中提取 httpHeader?

[英]How to extract httpHeader in WebClient response?

How can I extract the parameter "session-id" from http header, and write it into the response?如何从 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;
}

It is not possible with retrieve . retrieve是不可能的。 You need to use the exchange function instead of retrieve ,您需要使用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 网络客户端交换

Or with mutable object:或者使用可变对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM