【问题标题】:Get the total cookie size of a website given its header在给定标题的情况下获取网站的总 cookie 大小
【发布时间】:2017-10-11 20:53:05
【问题描述】:

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

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

我得到的字段结果为:

dwsid=H-GOhXnQOVZU1SKVvlnOMJOYZq5CNas9AUYMWArBVV00TnFO3a8VgoaUtl6wpJqgKWkidqt-y1ihDRm9yo3a7g==;路径=/; HttpOnly

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

【问题讨论】:

    标签: java http header session-cookies


    【解决方案1】:

    这里有一个快速的解决方案:

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

    【讨论】:

      【解决方案2】:

      在 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 字段的值)。


      bytes 的大小由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;
      

      【讨论】:

      • 太棒了! :) 如果有效,请将答案标记为已接受,以便其他人以后可以找到它
      • 完成!谢谢兄弟
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多