meylovezn 2019-10-30
python requests函数封装方法
上代码
import requests import json """ 封装request请求, 1.post:my_post 2.get:my_get 3.返回code:get_code(res) 4.返回json:get_json(res) 5.返回text:get_text(res) 6.响应时间:get_time(res) 7.请求header:get_header(act) 9.添加请求头参数:add_header(dict) """ #--------------------------------------------------- """ r.status_code r.text #页面内容 r.encoding #header中的编码方式 r.apparent_encoding #备选的编码方式 r.content #响应内容的二进制形式 timeout= r.elapsed.total_seconds(),单位是s """ #---------------------------------------------------- def my_post(url,payload,headers,timeout=30): res = requests.request("POST", url, data=payload, headers=headers,timeout=timeout) return res def my_get(url,payload,headers,querystring,timeout=30): resp = requests.request("GET", url, data=payload, headers=headers, params=querystring,timeout=timeout) #获取返回code code=res.status_code print(‘code‘,code) return res def get_code(res): #获取返回code code=res.status_code print(‘code:\n‘,code) def get_json(res): #获取返回json print(‘res.json:\n‘,res.json()) return res.json() def get_text(res): print(‘res.text:\n‘,res.text) return res.text def get_time(res): #获取响应执行时间,单位s time=res.elapsed.total_seconds() print(‘res.time:\n‘,res.elapsed.total_seconds()) return time def get_header(act): if act=="json": json_header={ ‘content-type‘: "application/json", } return json_header else: str_header={ ‘content-type‘: "application/x-www-form-urlencoded", } return str_header def add_header(dict): headers=get_header("json") for k,v in dict.items(): headers[k]=v return headers if __name__=="__main__": url="http://192.168.0.10:3080/asg/portal/call/231.do" #json转换格式 strData={"pub":{"deviceId":"dz630761d39e7145a3850eedc4563e61ff","subPline":"2","screen":"1080x1920","appCode":"f002","dzPaySupport":"2","userId":"16","city":"%E5%8C%97%E4%BA%AC","utdid":"WVXnflOMWeEDAG79IwDB2QuM","apiVersion":"3.9.7.3004","province":"%E5%8C%97%E4%BA%AC%E5%B8%82","v":"4","afu":"0","imei":"864141037331797","p":"55","clientAgent":"svnVer_1907171924","lsw":"1","apn":"wifi","imsi":"460016593620169","channelFee":"Google","cmTel":"","sign":"1ea70e2fc19f5da6f4bc926c35962559","pname":"com.ishugui","channelCode":"Google","os":"android23","brand":"Xiaomi","en":"{\"adsdk\":\"1\"}","macAddr":"AC:C1:EE:F8:D1:F6","model":"Redmi Note 4X"},"pri":{"v":"10","idStrs":"11000007217:25186137","sign_data":1,"is_sdk":"2","last_rcmbook_id":"","installedFreeApk":0,"index":3,"f":"f0,f1,f2,f3,f4,f5,f6,f7","sex":2,"vtv":"9"}} strJson=json.dumps(strData) print(‘strJson----- ‘,strJson) timeout=30 headers=get_header("json") res=my_post(url,strJson,headers,timeout) get_code(res) get_json(res) get_text(res)