问题
My problem is simple, I have to get the total cookie size (by bytes). I used the Http Header and called the set-cookie element:
public static String getCookiesField(URLConnection connection){
return connection.getHeaderField("Set-Cookie"); // it can return null
}
I get the result of the field as:
dwsid=H-GOhXnQOVZU1SKVvlnOMJOYZq5CNAs9AUYMWArBVV00TnFO3a8VgoaUtl6wpJqgKWkidqt-y1ihDRm9yo3a7g==; path=/; HttpOnly
I don't know what it mean but I need to get the size of the cookie by bytes.
回答1:
Call getBytes()
on the string of the cookie.
If you're unsure what the cookie is, mdn can help you; the syntax can be lots of different things, like
Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly; Path=<path-value>
// or
Set-Cookie: sessionid=38afes7a8; httponly; Path=/
The getHeaderField method returns a String
of the cookie (the value for the field Set-Cookie in the Header).
The size of the byte
s are calculated by myBytes.length
(no ()
).
So you can get the size of the cookie like this:
String setCookieField = connection.getHeaderField("Set-Cookie");
// check that cookie is not null
String[] cookieFields = cookie.split(";");
// the cookie name/value pair is typically first
String[] cookieNameValue = cookieFields[0].split("=");
String cookie = cookieNameValue[1];
int size = cookie.getBytes("UTF-8").length;
回答2:
Here's a quick solution:
String cookie = "dwsid=H-GOhXnQOVZU1SKVvlnOMJOYZq5CNAs9AUYMWArBVV00TnFO3a8VgoaUtl6wpJqgKWkidqt-y1ihDRm9yo3a7g==; path=/; HttpOnly".split(";");
bytes b[] = cookie[0].getBytes();
return b.length;
来源:https://stackoverflow.com/questions/43939368/get-the-total-cookie-size-of-a-website-given-its-header