Session Clients
If the client is a web browser then sessions should just work if you have cookies is enabled. However for programmatic HTTP clients you need to make sure you propagate the session id between HTTP calls.
For example, when invoking the viewCart
method of the StoreController
in the previous example the HTTP client will receive by default a AUTHORIZATION_INFO
header. The following example, using a Spock test, demonstrates this:
HttpResponse<Cart> response = client.exchange(HttpRequest.GET("/shopping/cart"), Cart.class) (1)
.blockingFirst();
Cart cart = response.body();
assertNotNull(response.header(HttpHeaders.AUTHORIZATION_INFO)); (2)
assertNotNull(cart);
assertTrue(cart.getItems().isEmpty());
when: "The shopping cart is retrieved"
HttpResponse<Cart> response = httpClient.exchange(HttpRequest.GET('/shopping/cart'), Cart) (1)
.blockingFirst()
Cart cart = response.body()
then: "The shopping cart is present as well as a session id header"
response.header(HttpHeaders.AUTHORIZATION_INFO) != null (2)
cart != null
cart.items.isEmpty()
var response = client.exchange(HttpRequest.GET<Cart>("/shopping/cart"), Cart::class.java) (1)
.blockingFirst()
var cart = response.body()
assertNotNull(response.header(HttpHeaders.AUTHORIZATION_INFO)) (2)
assertNotNull(cart)
cart.items.isEmpty()
1 | A request is made to /shopping/cart |
2 | The AUTHORIZATION_INFO header is present in the response |
You can then pass this AUTHORIZATION_INFO
in subsequent requests to re-use the existing Session:
String sessionId = response.header(HttpHeaders.AUTHORIZATION_INFO); (1)
response = client.exchange(
HttpRequest.POST("/shopping/cart/Apple", "")
.header(HttpHeaders.AUTHORIZATION_INFO, sessionId), Cart.class) (2)
.blockingFirst();
cart = response.body();
String sessionId = response.header(HttpHeaders.AUTHORIZATION_INFO) (1)
response = httpClient.exchange(
HttpRequest.POST('/shopping/cart/Apple', "")
.header(HttpHeaders.AUTHORIZATION_INFO, sessionId), Cart) (2)
.blockingFirst()
cart = response.body()
val sessionId = response.header(HttpHeaders.AUTHORIZATION_INFO) (1)
response = client.exchange(
HttpRequest.POST("/shopping/cart/Apple", "")
.header(HttpHeaders.AUTHORIZATION_INFO, sessionId), Cart::class.java) (2)
.blockingFirst()
cart = response.body()
1 | The AUTHORIZATION_INFO is retrieved from the response |
2 | And then sent as a header in the subsequent request |