Session Clients

If the client is a web browser, sessions should work if cookies are enabled. However, for programmatic HTTP clients you need to propagate the session ID between HTTP calls.

For example, when invoking the viewCart method of the StoreController in the previous example, the HTTP client receives by default a AUTHORIZATION_INFO header. The following example, using a Spock test, demonstrates this:

  1. HttpResponse<Cart> response = Flux.from(client.exchange(HttpRequest.GET("/shopping/cart"), Cart.class)) (1)
  2. .blockFirst();
  3. Cart cart = response.body();
  4. assertNotNull(response.header(HttpHeaders.AUTHORIZATION_INFO)); (2)
  5. assertNotNull(cart);
  6. assertTrue(cart.getItems().isEmpty());
  1. when: "The shopping cart is retrieved"
  2. HttpResponse<Cart> response = client.exchange(HttpRequest.GET('/shopping/cart'), Cart) (1)
  3. .blockFirst()
  4. Cart cart = response.body()
  5. then: "The shopping cart is present as well as a session id header"
  6. response.header(HttpHeaders.AUTHORIZATION_INFO) != null (2)
  7. cart != null
  8. cart.items.isEmpty()
  1. var response = Flux.from(client.exchange(HttpRequest.GET<Cart>("/shopping/cart"), Cart::class.java)) (1)
  2. .blockFirst()
  3. var cart = response.body()
  4. assertNotNull(response.header(HttpHeaders.AUTHORIZATION_INFO)) (2)
  5. assertNotNull(cart)
  6. cart.items.isEmpty()
1A request is made to /shopping/cart
2The AUTHORIZATION_INFO header is present in the response

You can then pass this AUTHORIZATION_INFO in subsequent requests to reuse the existing Session:

  1. String sessionId = response.header(HttpHeaders.AUTHORIZATION_INFO); (1)
  2. response = Flux.from(client.exchange(HttpRequest.POST("/shopping/cart/Apple", "")
  3. .header(HttpHeaders.AUTHORIZATION_INFO, sessionId), Cart.class)) (2)
  4. .blockFirst();
  5. cart = response.body();
  1. String sessionId = response.header(HttpHeaders.AUTHORIZATION_INFO) (1)
  2. response = client.exchange(HttpRequest.POST('/shopping/cart/Apple', "")
  3. .header(HttpHeaders.AUTHORIZATION_INFO, sessionId), Cart) (2)
  4. .blockFirst()
  5. cart = response.body()
  1. val sessionId = response.header(HttpHeaders.AUTHORIZATION_INFO) (1)
  2. response = Flux.from(client.exchange(HttpRequest.POST("/shopping/cart/Apple", "")
  3. .header(HttpHeaders.AUTHORIZATION_INFO, sessionId), Cart::class.java)) (2)
  4. .blockFirst()
  5. cart = response.body()
1The AUTHORIZATION_INFO is retrieved from the response
2And then sent as a header in the subsequent request