cookie的保存(or传递)

1 前言

web应用中经常见到,第一步尝试登陆;登录成功后,才能访问后续的接口。 

此文,仅以python和curl的演示。

2 Python

import json
import urllib.request
import http.cookiejar


class HttpUtil(object):
    def __init__(self):
        cookie = http.cookiejar.MozillaCookieJar()
        handler = urllib.request.HTTPCookieProcessor(cookie)
        self.opener = urllib.request.build_opener(handler)

    def api(self, **api_info):
        parm = api_info.get("parm", None)
        data = None

        global rep_status
        global rep_data

        # headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
        headers = {"Content-type": "application/json"}
        if parm:
            # data = urllib.parse.urlencode(api_info["parm"]).encode('utf-8')
            data = json.dumps(api_info["parm"]).encode('utf-8')

        if "headers" in api_info and api_info["headers"] != "":
            headers = api_info["headers"]

        try:
            request = urllib.request.Request(api_info["url"], data=data, headers=headers, method=api_info["method"])
            rep = self.opener.open(request)
            rep_status = rep.status
            rep_data = json.loads(rep.read())
        except urllib.error.URLError as e:
            rep_status = "URLError"
            rep_data = e

        return rep_status, rep_data


if __name__ == '__main__':
    http_util = HttpUtil()
    # first login
    rep_status, rep_data = http_util.api(url=url1, parm=parm1, method="POST")
    # 保存cookie后,可以访问其他接口了
    rep_status, rep_data = http_util.api(url=url2, parm=parm2, method="POST")
    print(rep_data)

 

 

3 curl

curl http://url:port/api/v1/login/ --cookie-jar ./login_cookie.txt  -X POST -H "Content-Type:application/json" -d '{"username":"username","password":"passord"}'

curl http://url:port/api/v1/submit/  --cookie ./login_cookie.txt  -X POST -H "Content-Type:application/json" -d '{"test":"test"}'

 

posted @ 2019-08-19 14:05  fly_pig  阅读(465)  评论(0编辑  收藏  举报