使用Cookie文件

如需让curl自动追踪服务器端Cookie,可以提供外部文件路径供curl维护Cookie。

选项-c--cookie-jar告知curl,当有Cookie更新时,将其写入指定的外部文件。curl会将当前域名下已有的Cookie和新增或修改的Cookie一起写入文件。

现在尝试访问第一个会设置Cookie的URL:

$ rm -f ~/cookie

$ curl -c ~/cookie -I -v http://localhost:8081/foo
> HEAD /foo HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/8.10.1
> Accept: */*
> 
< HTTP/1.1 404 Not Found
HTTP/1.1 404 Not Found
* Added cookie foo="1" for domain localhost, path /, expire 0
< Set-Cookie: foo=1
Set-Cookie: foo=1
(略)

$ cat ~/cookie 
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

localhost       FALSE   /       FALSE   0       foo     1

可见,Cookie已被写入文件中。让我们再尝试访问第二个设置Cookie的URL:

$ curl -c ~/cookie -I -v http://localhost:8081/bar
> HEAD /bar HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/8.10.1
> Accept: */*
> 
< HTTP/1.1 404 Not Found
HTTP/1.1 404 Not Found
* Added cookie bar="2" for domain localhost, path /, expire 0
< Set-Cookie: bar=2
Set-Cookie: bar=2
(略)

$ cat ~/cookie 
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

localhost       FALSE   /       FALSE   0       bar     2

奇怪的是,原先的Cookie:foo丢失了,只剩下本次请求的bar

其实,在初始状态,curl认为没有任何Cookie被设置,当请求/bar时,bar就是当前域名下唯一的Cookie了。

为了让curl知晓初始状态下已有的Cookie,需要使用-b选项,不过这次指定的是Cookie文件而不是字面值:

$ rm -f ~/cookie
$ curl -c ~/cookie -I http://localhost:8081/foo
$ curl -b ~/cookie -c ~/cookie -I http://localhost:8081/bar

 cat ~/cookie 
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

localhost       FALSE   /       FALSE   0       bar     2
localhost       FALSE   /       FALSE   0       foo     1

初始状态已有的Cookie也会随本次请求一起发送给服务器:

$ curl -b ~/cookie -c ~/cookie -v -I http://localhost:8081/baz
> HEAD /baz HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/8.10.1
> Accept: */*
> Cookie: foo=1; bar=2      # <== 已有的Cookie
> 
< HTTP/1.1 404 Not Found
HTTP/1.1 404 Not Found
< Set-Cookie: baz=3
Set-Cookie: baz=3
(略)

$ cat ~/cookie 
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

localhost       FALSE   /       FALSE   0       baz     3
localhost       FALSE   /       FALSE   0       foo     1
localhost       FALSE   /       FALSE   0       bar     2