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"}'

 

转载于:https://www.cnblogs.com/flypig258/p/11376774.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值