700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python 字典字符串转字典——urllib.request.Request发送get post请求 发送json参数

python 字典字符串转字典——urllib.request.Request发送get post请求 发送json参数

时间:2018-10-22 13:56:07

相关推荐

python 字典字符串转字典——urllib.request.Request发送get post请求 发送json参数

1.eval方法即可【字典字符串转字典】

file_content = eval(file_content)

2.urllib.request.Request发送post请求,发送json参数

from urllib.request import Request, urlopenimport json调用代码片段:url = 'http://www./api-sss/tdd/woRegulationCreate'header = {'tokenStr': "MTc2OF90b2tlbl8xNTQxNDg5NjA3MzYxLCwsMTU0MTQ4OTYwNzM2MQ==",'Content-Type': 'application/json'}post_data = {"evType": "曳引与强制驱动电梯","groupName": "半月保养(国际)","memo": "hui","count": "31/31","regullations":[{"name": "清洁","desc": "机房清洁","state": "1"}]}# post_data = urlencode(post_data).encode('utf-8')req = Request(url=url, data=json.dumps(post_data).encode('utf-8'), headers=header, method='POST')file_content = urlopen(req).read().decode('utf-8')print(type(file_content))print(file_content)

亲测可行

备注:以下是get方式和post方式请求数据

from urllib.request import Request, urlopenfrom urllib.parse import quote, urlencodeimport jsonfrom module.api_test.log_util import logsuccess_code = 0 # 请求成功的返回codeurl = 'http://172.16.2.74:8080/workOrder/detail'params = Noneheader = {'Authorization': "MTc2OF90b2tlbl8xNTQzMjg1MjAyMDU3LCwsMTU0MzI4NTIwMjA1Nw==",'Content-Type': 'application/json'}post_body = {}def post_api(url, params: dict, header: dict, post_body: dict):"""尝试POST方式请求接口:param url::param params::param header::param post_body::return:"""if header and "Content-Type" in header.keys() and header['Content-Type'] == 'application/json': # 请求参数是jsonreq = Request(url=url, data=json.dumps(post_body).encode('utf-8'), headers=header, method='POST')else: # 请求参数是mapparams = urlencode(params).encode('utf-8') # 编码请求参数req = Request(url=url, data=params, headers=header, method='POST')process_result(req)def get_api(url, params: dict, header: dict):"""尝试GET方式请求接口:param url::param params: quote(params[key], safe='/', encoding='utf-8', errors=None) 防止中文编码错误问题:param header::return:"""get_params = Noneif params:for key in params.keys():if params[key]:if not get_params:get_params = "?" + quote(key, safe='/', encoding='utf-8', errors=None) + "=" + quote(params[key],safe='/',encoding='utf-8',errors=None)else:get_params += "&" + quote(key, safe='/', encoding='utf-8', errors=None) + "=" + quote(params[key],safe='/',encoding='utf-8',errors=None)if get_params:url += get_paramsif header:req = Request(url=url, headers=header, method='GET')else:req = Request(url=url, method='GET')process_result(req)def process_result(req):"""处理请求返回结果:param req::return:"""result_content = Nonetry:result_content = urlopen(req).read().decode('utf-8')result_content = json.loads(result_content)if result_content['code'] and not result_content['code'] == success_code:log('------操作失败------')log('request_url:' + url)log('request_params:' + str(params))log('response:' + str(result_content))else:log('------操作成功------')log(str(result_content))except Exception as excp:log('------请求异常------')log('request_url:' + url)log('request_params:' + str(params))log('response:' + str(result_content))log('error:' + str(excp))if __name__ == '__main__':# url = "http://172.16.2.74:8080/elevator/getEvList"# params = {'cityId': "2282", "projectName": "花满楼", "page": "1", "pageSize": "11"}# get_api(url, params, header)# url = 'http://172.16.2.74:8080/alarm/wxAlarm'# params = {# "description": "",# "evId": "197363018554679296",# "openId": "o8xzN0eBwTNVYbnbxF7qf5H928gw",# "trap": 1# }# post_api(url,params,header,params)url = 'http://api./api-elorr/elevatorInfo/updateElevatorFileNumber'header = {'tokenStr': "MTc2OF90b2tlbl8xNTQzMzk4NzEzMDUyLCwsMTU0MzM5ODcxMzA1Mg=="}params = {"evId": "197363018554679296","fileNumber": "o8xzN0eBwTNVYbnbxF7qf5H928gw"}post_api(url, params, header, params)

————————————————

版权声明:本文为CSDN博主「风正吹」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

原文链接:/yingtian648/article/details/83788638

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。