Reputation: 13
I'm trying to make a resource which adds products into a shopping cart. I'm trying to add a product to the shopping cart and save the shopping cart as JSON String in a cookie. (Here the Cart object has 2 fields, productId and quantity)
@POST
@Path("/update")
@Produces(MediaType.APPLICATION_JSON)
public Response updateShoppingCart(@CookieParam(COOKIE_NAME) javax.ws.rs.core.Cookie cookie, Cart cart) {
NewCookie newCookie = null;
ObjectMapper mapper = new ObjectMapper();
if (cookie !=null){
try {
List<Cart> shoppingCart = mapper.readValue(cookie.getValue(), new TypeReference<List<Cart>>() {
});
//the case where there is already something in the shopping cart
//...
String jsonString = mapper.writeValueAsString(shoppingCart);
newCookie = new NewCookie(COOKIE_NAME, jsonString,"/", "", "shopping-cart", MAX_AGE, false);
} catch (IOException e) {
e.printStackTrace();
}
}else{
List<Cart> carts = new ArrayList<>();
carts.add(cart);
try {
String jsonString = mapper.writeValueAsString(carts);
newCookie = new NewCookie(COOKIE_NAME, jsonString,"/", "", "shopping-cart", MAX_AGE, false);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
return Response.ok(newCookie).cookie(newCookie).build();
}
The first time when I run this, the cookie is set correctly for example it sets the correct value: [{\"productId\":1,\"quantity\":2}] if I add a product with the id 1 and quantity 2. The problem is that when I run this a second time the cookie received as CookieParam has an incorrect value, in this case [{\"productId\":1 . I'm testing this with Postman and sending a POST request with the JSON {"productId":1, "quantity":2} in the body. What am I doing wrong?
Upvotes: 1
Views: 796
Reputation: 1296
Cookies have to be put in the header, not the body. Something like:
Cookie: name=value; name2=value2; name3=value3
For postman refer to : https://www.getpostman.com/docs/postman/sending_api_requests/cookies
UPDATE: In my experience, postman sometimes does not send cookies. Try converting postman command to curl command (refer to: https://www.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets) then make sure curl command has the cookie either in the header or in -b parameter (Refer: https://curl.haxx.se/docs/manpage.html)
Upvotes: 1