简体   繁体   中英

How can I parse a specific cookie from this string in Java?

say I have the following string in a variable

cookie-one=someValue;HttpOnly;Secure;Path=/;SameSite=none, cookie-two=someOtherValue;Path=/;Secure;HttpOnly, cookie-three=oneMoreValue;Path=/;Secure

and I want a substring from the name of a cookie that I choose say cookie-two and store the string up to the contents of that cookie.

So basically I need

cookie-two=someOtherValue;Path=/;Secure;HttpOnly

How can I get this substring out?

You can just separate the String by commas first to separate the cookies. For example if you wanted just the cookie that has the name cookie-two :

String s = "cookie-one=someValue;HttpOnly;Secure;Path=/;SameSite=none, cookie-two=someOtherValue;Path=/;Secure;HttpOnly, cookie-three=oneMoreValue;Path=/;Secure";

String[] cookies = s.split(",");
for(String cookie : cookies){
  if(cookie.trim().startsWith("cookie-two")){
    System.out.println(cookie);
  }
}

This is possible to achieve in several different ways depending on how the data might vary in the sting. For your specific example we could for instance do like this:

String cookieString = "cookie-one=someValue;HttpOnly;Secure;Path=/;SameSite=none, cookie-two=someOtherValue;Path=/;Secure;HttpOnly, cookie-three=oneMoreValue;Path=/;Secure";
String result = "";
for(String s: cookieString.split(", ")) {
    if(s.startsWith("cookie-two")) {
        result = s;
        break;
    }
}

We could also use regex and/or streams to make the code look nicer, but this is probably one of the most straight forward ways of achieving what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM