获取给定标题的网站的总 cookie 大小



我的问题很简单,我必须得到总的cookie大小(按字节)。我使用了 Http 标头并调用了 set-cookie 元素:

public static String getCookiesField(URLConnection connection){
return connection.getHeaderField("Set-Cookie"); // it can return null
}

我得到字段的结果为:

dwsid=H-GOhXnQOVZU1SKVvlnOMJOYZq5CNAs9AUYMWArBVV00TnFO3a8VgoaUtl6wpJqgKWkidqt-y1ihDRm9yo3a7g==; 路径=/;仅 httponly

我不知道这是什么意思,但我需要按字节获取 cookie 的大小。

在 cookie 的字符串上调用getBytes()

如果你不确定cookie是什么,mdn可以帮助你;语法可以是很多不同的东西,比如

Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly; Path=<path-value>
// or 
Set-Cookie: sessionid=38afes7a8; httponly; Path=/

getHeaderField 方法返回 cookie 的String(标头中字段Set-Cookie 的值)。


byte的大小按myBytes.length计算(无())。

因此,您可以像这样获得cookie的大小:

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;

这是一个快速的解决方案:

String cookie = "dwsid=H-GOhXnQOVZU1SKVvlnOMJOYZq5CNAs9AUYMWArBVV00TnFO3a8VgoaUtl6wpJqgKWkidqt-y1ihDRm9yo3a7g==; path=/; HttpOnly".split(";");
bytes b[] = cookie[0].getBytes();
return b.length;

最新更新