📜  Java Java

📅  最后修改于: 2022-05-13 01:55:36.409000             🧑  作者: Mango

Java Java

先决条件 - Cookie

许多网站使用称为 cookie 的小文本字符串来存储连接之间的持久客户端状态。 Cookie 在请求和响应的 HTTP 标头中从服务器传递到客户端并再次返回。服务器可以使用 Cookie 来指示会话 ID、购物车内容、登录凭据、用户偏好等。

一个 HttpCookie 对象代表一个 http cookie,它携带服务器和用户代理之间的状态信息。 Cookie 被广泛用于创建有状态会话。
有 3 个 http cookie 规范:

  • 网景草稿
  • RFC 2109
  • RFC 2965

HttpCookie 类可以接受所有这 3 种语法形式。

构造函数:创建具有指定名称和值的 cookie。名称必须仅包含 ASCII 字母数字字符并符合 RFC 2965。如果名称不正确,则会引发 IllegalArgument 异常;如果名称为 null,则会引发 NullPointerException。该值可以是任何 cookie 想要存储的值。

Syntax : public HttpCookie(String name,
          String value)
Parameters :
name : name of cookie
value : value of cookie
Throws :
IllegalArgumentException : if name does not conform to RFC2965
NullPointerException : if name is null

方法 :

  1. parse() :返回从标头字符串解析的 cookie 列表。标头必须以 set-cookie 或 set-cookie2 令牌开头,或者根本不能包含任何令牌。
    Syntax : public static List parse(String header)
    Parameters : 
    header : String to be parsed as cookies
  2. hasExpired() :返回布尔值,指示 cookie 是否已过期。
    Syntax : public boolean hasExpired()
  3. setComment() :用于设置描述 cookie 用途的简短描述。它用于向用户显示 cookie。
    Syntax : public void setComment(String purpose)
    Parameters :
    purpose : purpose of cookie
  4. getComment() :返回 cookie 的描述,如果 cookie 没有评论,则返回 null。
    Syntax : public void getComment()
  5. setCommentURL() :用于设置描述 cookie 用途的简短评论 url。它在浏览器向用户呈现 cookie 时使用。
    Syntax : public void setCommentURL(String purpose)
    Parameters :
    purpose : purpose of cookie
  6. getCommentURL() :返回 cookie 的 URL 注释,如果 cookie 没有 URL 注释,则返回 null。
    Syntax : public String getComment()
  7. setDiscard() :用于设置用户代理是否应丢弃此 cookie。
    Syntax : public void setDiscard(Boolean discard)
    Parameters :
    discard : true if UA should discard, otherwise false
  8. getDiscard() :返回由 setDiscard() 方法设置的丢弃变量的状态。更具体地说,如果 UA 要丢弃此 cookie,则返回 true,否则返回 false。
    Syntax : public Boolean getDiscard()
  9. setPortList() :用于指定此 cookie 可以使用的端口。
    Syntax : public void setPortList(String portList)
    Parameters :
    portList : String of comma separated digits specifying the ports.
  10. getPortList() :返回此 cookie 可以使用的端口列表。
    Syntax : public String getPortList()
  11. setDomain() :指定此 cookie 应该在其中可见的域。例如,从 bali.vacations.com 的 servlet 发送的 cookie 通常不会被浏览器返回到 queensland.vacations.com 的页面。如果站点希望发生这种情况,servlet 可以指定 cookie.setDomain(“.vacations.com”)。为防止服务器设置应用于其域外主机的 cookie,指定域必须满足以下要求:它必须以点开头(例如,.coreservlets.com)。
    Syntax : public void setDomain(String domain)
    Parameters :
    domain : String representing the domain in which this cookie is visible
  12. getDomain() :返回此 cookie 可见的域。
    Syntax : public String getDomain()
  13. setMaxAge() :用于设置 cookie 的最大年龄(以秒为单位)。它指定创建 cookie 后它处于活动状态的最长时间。负值指定 cookie 将在浏览器退出后立即过期。
    Syntax : public void setMaxAge(long age)
    Parameters :
    age : Max survive time in seconds
  14. getMaxAge() :返回 cookie 的最大年龄。
    Syntax : public long getMaxAge()
  15. setPath() :用于指定客户端返回 cookie 的路径。此 cookie 对指定路径的所有页面和子目录可见。例如,如果服务器从 http://ecommerce.site.com/toys/specials.html 发送 cookie,浏览器将在连接到 http://ecommerce.site.com/to/beginners 时将 cookie 发回。 html,但不是 http://ecommerce.site.com/c/classic.html。
    Syntax : public void setPath(String uri)
    Parameters :
    uri - a String specifying a path
  16. getPath() :返回为此 cookie 设置的路径。
    Syntax : public String getPath()

    Java实现:

    // Java Program to illustrate various
    // methods of java.net.HttpCookie class
    public class httpcookie1 
    {
      
        public static void main(String[] args) 
        {
      
            // Constructor to create a new cookie.
            HttpCookie cookie = new HttpCookie("First", "1");
      
            // setComment() method
            cookie.setComment("Just for explanation");
      
            // getComment() method
            System.out.println("Comment : " + cookie.getComment());
      
            // setCommentURL() method
            cookie.setCommentURL("192.168.1.1");
      
            // getCommentURL() method
            System.out.println("CommentURL : " + cookie.getCommentURL());
      
            // setDiscard() method
            cookie.setDiscard(true);
      
            // getDiscard() method
            System.out.println("Discard : " + cookie.getDiscard());
      
            // setPortlist() method
            cookie.setPortlist("1001,8520");
      
            // getPortList() method
            System.out.println("Ports: " + cookie.getPortlist());
      
            // setDomain() method
            cookie.setDomain(".localhost.com");
      
            // getDomain() method
            System.out.println("Domain : " + cookie.getDomain());
      
            // setMaxAge() method
            cookie.setMaxAge(3600);
      
            // getMaxAge() method
            System.out.println("Max Age : " + cookie.getMaxAge());
      
            // setPath() method
            cookie.setPath("192.168.1.1/admin/index.html");
      
            // getPath() method
            System.out.println("Path: " + cookie.getPath());
      
        }
      
    }
    

    输出

    Comment : Just for explanation
    CommentURL : 192.168.1.1
    Discard : true
    Ports: 1001,8520
    Domain : .localhost.com
    Max Age : 3600
    Path: 192.168.1.1/admin/index.html
  17. setSecure() :指示发送此 cookie 时是否使用安全协议。默认值为假。
    Syntax : public void setSecure(boolean secure)
    Parameters:
    secure - If true, the cookie can only be sent over a secure protocol like https. 
    If false, it can be sent over any protocol.
  18. getSecure() :如果此 cookie 必须由安全协议发送,则返回 true,否则返回 false。
    Syntax : public boolean getSecure()
  19. getName() :返回 cookie 的名称。
    Syntax : public String getName()
  20. setValue() :初始化后为 cookie 分配新值。
    Syntax : public void setValue(String newValue)
    Parameters :
    newValue - a String specifying the new value
  21. getValue :返回 cookie 的值。
    Syntax : public String getValue()
  22. getVersion() :如果 cookie 符合原始 Netscape 规范,则返回 0; 1 如果 cookie 符合 RFC 2965/2109
    Syntax : public int getVersion()
  23. setVersion() :用于设置此 cookie 使用的 cookie 协议的版本。
    Syntax :public void setVersion(int v)
                   throws IllegalArgumentException
    Parameters :
    v - 0 for original Netscape specification; 1 for RFC 2965/2109
    Throws :
    IllegalArgumentException - if v is neither 0 nor 1
  24. isHttpOnly() :如果 cookie 只能被 http 使用,即它不能被 JS、vb 等脚本语言使用,则返回 true。
    Syntax : public boolean isHttpOnly()
  25. setHttpOnly() :用于设置此 cookie 是否仅为 http。
    Syntax : public void setHttpOnly(boolean httpOnly)
    Parameters :
    httpOnly - if true make the cookie HTTP only, i.e. only visible as part 
    of an HTTP request.
  26. domainMatches() :检查主机名是否在域中的实用函数。
    Syntax : public static boolean domainMatches(String domain,
                        String host)
    Parameters :
    domain : domain to check hostname with
    host : host to check
  27. toString() :构造此 cookie 的字符串表示形式。
    Syntax :public String toString()
  28. equals() :如果两个 http cookie 相等则返回 true,否则返回 false。
    Syntax :public boolean equals(Object obj)
  29. hashCode() :返回这个 http cookie 的哈希码。结果是此 cookie 的三个重要组成部分的哈希码值的总和:名称、域和路径。覆盖类 Object 中的 hashCode。
    Syntax : public int hashCode()
  30. clone() :创建并返回此对象的副本。覆盖对象类的克隆方法。
    Syntax : public Object clone()

Java实现:

// Java Program to illustrate various
// methods of java.net.HttpCookie class
import java.net.HttpCookie;
  
public class httpcookie1 
{
  
    public static void main(String[] args) 
    {
  
        // Constructor to create a new cookie.
        HttpCookie cookie = new HttpCookie("First", "1");
  
        // setSecure() method
        cookie.setSecure(true);
  
        // getSecure() method
        System.out.println("Secure : " + cookie.getSecure());
  
        // getName() method
        System.out.println("Name : " + cookie.getName());
  
        // setValue() method : can be used to modify value of cookie.
        cookie.setValue("2");
  
        // getvalue() method
        System.out.println("Value : " + cookie.getValue());
  
        // setVersion() method
        cookie.setVersion(1);
  
        // getVersion() method
        System.out.println("Version : " + cookie.getVersion());
  
        // setHttPonly() method
        cookie.setHttpOnly(true);
  
        // isHttpOnly() method
        System.out.println("is HTTP only : " + cookie.isHttpOnly());
  
        // toString() method
        System.out.println("toString : " + cookie.toString());
  
        // hashcode() method
        System.out.println("Hashcode : " + cookie.hashCode());
  
    }
  
}

输出 :

Secure : true
Name : First
Value : 2
Version : 1
is HTTP only : true
toString : First="2"
Hashcode : 97440432

另一个显示 Web 服务器如何实际使用 cookie 的示例,我们在其中打印 www.facebook.com 存储的 cookie 的详细信息

import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
  
public class httpcookie1 
{
  
    public static void main(String[] args) throws IOException 
    {
  
        String urlString = "https://www.facebook.com";
  
        // Create a default system-wide CookieManager
        CookieManager cookieManager = new CookieManager();
  
        CookieHandler.setDefault(cookieManager);
  
        // Open a connection for the given URL
        URL url = new URL(urlString);
        URLConnection urlConnection = url.openConnection();
        urlConnection.getContent();
  
        // Get CookieStore which is the default internal in-memory
        CookieStore cookieStore = cookieManager.getCookieStore();
  
        // Retrieve all stored HttpCookies from CookieStore
        List cookies = cookieStore.getCookies();
  
        int cookieIdx = 0;
  
        // Iterate HttpCookie object
        for (HttpCookie ck : cookies) {
  
            System.out.println("------ Cookie." + ++cookieIdx + " -------");
  
            // Get the cookie name
            System.out.println("Cookie name: " + ck.getName());
  
            // Get the domain set for the cookie
            System.out.println("Domain: " + ck.getDomain());
  
            // Get the max age of the cookie
            System.out.println("Max age: " + ck.getMaxAge());
  
            // Get the path of the server
            System.out.println("Server path: " + ck.getPath());
  
            // Get boolean if the cookie is being restricted to a secure
            // protocol
            System.out.println("Is secured: " + ck.getSecure());
  
            // Gets the value of the cookie
            System.out.println("Cookie value: " + ck.getValue());
  
            // Gets the version of the protocol with which the given cookie is
            // related.
            System.out.println("Cookie protocol version: " + ck.getVersion());
  
        }
    }
  
}

输出 :

------------------ Cookie.1 ------------------
Cookie name: fr
Domain: .facebook.com
Max age: 7775999
Server path: /
Is secured: true
Cookie value: 0Xj7tBSsWlmtXPo92..BZFC8G.qC.AAA.0.0.BZFC8G.AWUwiIgM
Cookie protocol version: 0

参考:
官方Java文档