Sets a cookie for the given URL. Any existing cookie with the same host, path and name will be replaced with the new cookie. The cookie being set must not have expired and must not be a session cookie, otherwise it will be ignored.

url

the URL for which the cookie is set

value

the cookie as a string, using the format of the 'Set-Cookie' HTTP response header

value参数的作用是cookie值的字符串形式,但格式一定要是http请求头格式"Set-Cookie"。

api文档里的这句话突然让我惊醒,于是经过百度我查到了cookie的格式相关的文章,现摘抄如下:

原文链接:http://www.cnblogs.com/hdtianfu/archive/2013/05/30/3108295.html

Cookie相关的Http头

有连个Http头部和Cookie有关:Set-Cookie和Cookie。

Set-Cookie由服务器发送,它包含在响应请求的头部中。它用于在客户端创建一个Cookie

Cookie头由客户端发送,包含在HTTP请求的头部中。注意,只有cookie的domain和path与请求的URL匹配才会发送这个cookie。

Set-Cookie Header

Set-Cookie响应头的格式如下所示:

Set-Cookie: =[; =]...

[; expires=][; domain=]

[; path=][; secure][; httponly]

expires=: 设置cookie的有效期,如果cookie超过date所表示的日期时,cookie将失效。

如果没有设置这个选项,那么cookie将在浏览器关闭时失效。

注意:date是格林威治时间(GMT),使用如下格式表示:

DAY, DD MMM YYYY HH:MM:SS GMT

DAY

The day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).

DD

The day in the month (such as 01 for the first day of the month).

MMM

The three-letter abbreviation for the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).

YYYY

The year.

HH

The hour value in military time (22 would be 10:00 P.M., for example).

MM

The minute value.

SS

The second value.

domain= :

path=:

注:临时cookie(没有expires参数的cookie)不能带有domain选项。

当客户端发送一个http请求时,会将有效的cookie一起发送给服务器。

如果一个cookie的domain和path参数和URL匹配,那么这个cookie就是有效的。

secure   : 表示cookie只能被发送到http服务器。

httponly : 表示cookie不能被客户端脚本获取到。

在程序中生成expires

C的方式

time_t curTime = time(NULL);

tm * gmTime = gmtime(&curTime);

char strExperis[50];

strftime(strTimeBuf, 100, " %a, %d %b %Y %X GMT;", gmTime);

JavaScript的方式

var d = new Date();

var expires = d.toGMTString();

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐