根据标题获得网站的总Cookie大小 [英] Get the total cookie size of a website given its header
问题描述
我的问题很简单,我必须获取Cookie的总大小(按字节计).我使用了Http标头,并将其称为set-cookie元素:
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
}
我得到的字段结果为:
dwsid = H-GOhXnQOVZU1SKVvlnOMJOYZq5CNAs9AUYMWArBVV00TnFO3a8VgoaUtl6wpJqgKWkidqt-y1ihDRm9yo3a7g ==;路径=/; HttpOnly
dwsid=H-GOhXnQOVZU1SKVvlnOMJOYZq5CNAs9AUYMWArBVV00TnFO3a8VgoaUtl6wpJqgKWkidqt-y1ihDRm9yo3a7g==; path=/; HttpOnly
我不知道这是什么意思,但我需要按字节获取cookie的大小.
I don't know what it mean but I need to get the size of the cookie by bytes.
推荐答案
在Cookie的字符串上调用getBytes()
.
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=/
getHeaderField 方法返回cookie的String
(标题中Set-Cookie字段的值).
The getHeaderField method returns a String
of the cookie (the value for the field Set-Cookie in the Header).
byte
的大小由myBytes.length
计算(没有()
).
The size of the byte
s are calculated by myBytes.length
(no ()
).
因此,您可以像这样获取Cookie的大小:
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;
这篇关于根据标题获得网站的总Cookie大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!