1

如何从 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;
}
4

1 回答 1

3

这是不可能的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;
}

网络客户端交换

或使用可变对象:

...
.exchange()
    .flatMap(rsp -> {
       String id = rsp.headers().asHttpHeaders().getFirst("session-id");
       return rsp.bodyToMono(MyResponse.class)
              .doOnNext(next -> rsp.setHttpHeaderSessionId(id));
    })
    .block();
于 2019-07-10T12:28:37.587 回答