Get the total cookie size of a website given its header

一笑奈何 提交于 2019-12-11 06:14:56

问题


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 bytes 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!