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:

  1. HttpResponse<Cart> response = client.exchange(HttpRequest.GET("/shopping/cart"), Cart.class) (1)
  2. .blockingFirst();
  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 = httpClient.exchange(HttpRequest.GET('/shopping/cart'), Cart) (1)
  3. .blockingFirst()
  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 = client.exchange(HttpRequest.GET<Cart>("/shopping/cart"), Cart::class.java) (1)
  2. .blockingFirst()
  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 re-use the existing Session:

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