Java: Is there an easy way to get a cookie by name?

I was looking for solutions on how to get cookies by their name, and all solutions point to the use of for-loops and if . See code below.

 for (Cookie cookie : cookies) { if (cookie.getName().equals("<NAME>")) { // do something here } if (cookie.getName().equals("<ANOTHER_NAME>")) { // do something here } // and so on... } 

Is there any simpler way to get the value by their name without having to do loops, and what if?

I need to do some “specific” processing for certain cookies that I would like to receive Plus, I don’t want to go through every cookie! There may be 10 or more, and all I need is just three or something like that.

+5
source share
2 answers

Logic (as suggested by Matt Ball in the comments):

 // ... Map<String, Cookie> cookieMap = new HashMap<>(); for (Cookie cookie : cookies) { cookieMap.put(cookie.getName(), cookie); } Cookie firstRequiredCookie = cookieMap.get("<NAME>"); // do something with firstRequiredCookie Cookie nextRequiredCookie = cookieMap.get("<ANOTHER_NAME>"); // do something with nextRequiredCookie // ... 
0
source

Cookie names are not unique, so using a cookie name as a card key is not an ideal approach.

Since cookie names are not unique, it is possible why this Java API has never been updated to provide the getCookieByName() method.

0
source

Source: https://habr.com/ru/post/1215105/


All Articles