首页 文章

如何使用cURL发送Cookies?

提问于
浏览
217

我读到Send cookies with curl有效,但不适合我

我有一个 REST endpoints

class LoginResource(restful.Resource):
    def get(self):
        print(session)
        if 'USER_TOKEN' in session:
            return 'OK'
        return 'not authorized', 401

当我尝试访问时

curl -v -b ~/Downloads/cookies.txt -c ~/Downloads/cookies.txt http://127.0.0.1:5000/
* About to connect() to 127.0.0.1 port 5000 (#0)
*   Trying 127.0.0.1...
* connected
* Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.27.0
> Host: 127.0.0.1:5000
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 401 UNAUTHORIZED
< Content-Type: application/json
< Content-Length: 16
< Server: Werkzeug/0.8.3 Python/2.7.2
< Date: Sun, 14 Apr 2013 04:45:45 GMT
<
* Closing connection #0
"not authorized"%

我的 ~/Downloads/cookies.txt 在哪里

cat ~/Downloads/cookies.txt
USER_TOKEN=in

并且服务器什么也没收到

127.0.0.1 - - [13/Apr/2013 21:43:52] "GET / HTTP/1.1" 401 -
127.0.0.1 - - [13/Apr/2013 21:45:30] "GET / HTTP/1.1" 401 -
<SecureCookieSession {}>
<SecureCookieSession {}>
127.0.0.1 - - [13/Apr/2013 21:45:45] "GET / HTTP/1.1" 401 -

我错过了什么?

3 回答

  • 17

    这对我有用

    curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/
    

    我可以看到后端使用的值

    print request.cookies
    
  • 362

    您可以参考https://curl.haxx.se/docs/http-cookies.html获取有关如何使用cookie的完整教程 . 您可以使用

    curl -c /path/to/cookiefile http://yourhost/
    

    写入cookie文件并启动引擎并使用您可以使用的cookie

    curl -b /path/to/cookiefile  http://yourhost/
    

    从中读取cookie并启动cookie引擎,或者如果它不是文件,它将传递给定的字符串 .

  • 57

    您在cookie文件中使用了错误的格式 . 正如curl documentation所述,它使用旧的Netscape cookie文件格式,这与Web浏览器使用的格式不同 . 如果您需要手动创建curl cookie文件,this post应该可以帮到您 . 在您的示例中,该文件应包含以下行

    127.0.0.1   FALSE   /   FALSE   0   USER_TOKEN  in
    

    具有7个TAB分隔字段,表示域,尾部匹配,路径,安全,过期,名称,值 .

相关问题