Как извлечь httpHeader в ответ WebClient? - PullRequest
0 голосов
/ 10 июля 2019

Как извлечь из заголовка http параметр "идентификатор сессии" и записать его в ответ?

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;
}

1 Ответ

1 голос
/ 10 июля 2019

Вы не можете использовать функцию 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();
...