先决条件—— 曲奇饼
许多网站使用称为cookie的小文本字符串来存储连接之间的持久客户端状态。Cookie从服务器传递到客户端,然后在请求和响应的HTTP头中再次传递。服务器可以使用cookie来指示会话ID、购物车内容、登录凭据、用户首选项等。
HttpCookie对象表示http cookie,它在服务器和用户代理之间传输状态信息。Cookie被广泛用于创建有状态会话。 有3种http cookie规范:
HttpCookie类可以接受这三种形式的语法。
建造师: 创建具有指定名称和值的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
方法:
- parse(): 返回从标题字符串解析的cookie列表。标头必须以set-cookie或set-cookie2令牌开头,或者不能包含任何令牌。
Syntax : public static List parse(String header) Parameters : header : String to be parsed as cookies
- 已过期(): 返回指示cookie是否已过期的布尔值。
Syntax : public boolean hasExpired()
- setComment(): 用于设置描述cookie用途的简短描述。它用于向用户呈现cookie。
Syntax : public void setComment(String purpose) Parameters : purpose : purpose of cookie
- getComment(): 返回cookie的描述,如果cookie没有注释,则返回null。
Syntax : public void getComment()
- setCommentURL(): 用于设置描述cookie用途的简短注释url。当浏览器向用户呈现cookie时使用。
Syntax : public void setCommentURL(String purpose) Parameters : purpose : purpose of cookie
- getCommentURL(): 返回cookie的URL注释,如果cookie没有URL注释,则返回null。
Syntax : public String getComment()
- setDiscard(): 用于设置用户代理是否应丢弃此cookie。
Syntax : public void setDiscard(Boolean discard) Parameters : discard : true if UA should discard, otherwise false
- getDiscard(): 返回setDiscard()方法设置的discard变量的状态。更具体地说,如果UA要丢弃此cookie,则返回true,否则返回false。
Syntax : public Boolean getDiscard()
- setPortList(): 用于指定此cookie可以使用的端口。
Syntax : public void setPortList(String portList) Parameters : portList : String of comma separated digits specifying the ports.
- getPortList(): 返回此cookie可以使用的端口列表。
Syntax : public String getPortList()
- setDomain(): 指定此cookie应在其中可见的域。例如,从巴厘岛的servlet发送的cookies。假期。com通常不会通过浏览器返回到昆士兰的页面。假期。通用域名格式。如果站点希望这样做,servlet可以指定cookie。setDomain(“.vacations.com”)。为了防止服务器设置应用于其域外主机的cookie,指定的域必须满足以下要求:它必须以点开头(例如.coreservlet.com)。
Syntax : public void setDomain(String domain) Parameters : domain : String representing the domain in which this cookie is visible
- getDomain(): 返回此cookie可见的域。
Syntax : public String getDomain()
- setMaxAge(): 用于设置cookie的最大保存时间(秒)。它指定创建cookie后其处于活动状态的最长时间。负值指定浏览器退出后cookie将立即过期。
Syntax : public void setMaxAge(long age) Parameters : age : Max survive time in seconds
- getMaxAge(): 返回cookie的最大年龄。
Syntax : public long getMaxAge()
- setPath(): 用于指定客户端返回cookie的路径。此cookie对指定路径的所有页面和子目录都可见。例如,如果服务器从http://ecommerce.site.com/toys/specials.html,浏览器会在连接到时将cookie发回http://ecommerce.site.com/to/beginners.html,但不是http://ecommerce.site.com/c/classic.html.
Syntax : public void setPath(String uri) Parameters : uri - a String specifying a path
- 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
- setSecure(): 指示发送此cookie时是否使用安全协议。默认值为false。
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.
- getSecure(): 如果此cookie必须通过安全协议发送,则返回true,否则返回false。
Syntax : public boolean getSecure()
- getName(): 返回cookie的名称。
Syntax : public String getName()
- setValue(): 初始化后为cookie分配新值。
Syntax : public void setValue(String newValue) Parameters : newValue - a String specifying the new value
- getValue: 返回cookie的值。
Syntax : public String getValue()
- getVersion(): 如果cookie符合最初的Netscape规范,则返回0;1如果cookie符合RFC 2965/2109
Syntax : public int getVersion()
- 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
- isHttpOnly(): 如果cookie只能由http ie使用,则返回true。它不能由JS、vb等脚本语言使用。
Syntax : public boolean isHttpOnly()
- 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.
- domainMatches(): 实用程序函数,用于检查主机名是否在域中。
Syntax : public static boolean domainMatches(String domain, String host) Parameters : domain : domain to check hostname with host : host to check
- toString(): 构造此cookie的字符串表示形式。
Syntax :public String toString()
- 等于(): 如果两个http cookie彼此相等,则返回true,否则返回false。
Syntax :public boolean equals(Object obj)
- hashCode(): 返回此http cookie的哈希代码。结果是这个cookie的三个重要组件:名称、域和路径的哈希代码值之和。重写类对象中的哈希代码。
Syntax : public int hashCode()
- 克隆(): 创建并返回此对象的副本。重写对象类的克隆方法。
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
另一个例子展示了网络服务器如何实际使用cookie,我们在其中打印了www.facebook存储的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 { // 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<HttpCookie> 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文档
本文由 Rishabh Mahrsee .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。