接口基本信息
接口地址:http://127.0.0.1:8080/testpro/api/common/service
调用方式:POST
参数:JSON格式字符串,放到独立的.json文件中
返回:调用码返回200
且,返回内容有效,则验证成功
代码示例
使用urllib.request调用接口
urlopen()只能用于一些简单的资源请求
# 爬百度数据from urllib import requestresponse = request.urlopen("")fi = open("my_baidu.txt","w")page = fi.write(str(response.read()))fi.close()//必须要关闭资源#处理get请求,不传data,则为get请求import urllibfrom urllib.request import urlopenfrom urllib.parse import urlencodeurl='/login'data={"username":"admin","password":123456}req_data=urlencode(data)#将字典类型的请求数据转变为url编码res=urlopen(url+'?'+req_data)#通过urlopen方法访问拼接好的urlres=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为strprint(res)#处理post请求,如果传了data,则为post请求import urllibfrom urllib.request import Requestfrom urllib.parse import urlencodeurl='/login'data={"username":"admin","password":123456}data=urlencode(data)#将字典类型的请求数据转变为url编码data=data.encode('ascii')#将url编码类型的请求数据转变为bytes类型req_data=Request(url,data)#将url和请求数据处理为一个Request对象,供urlopen调用with urlopen(req_data) as res:res=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为strprint(res)
示例二 :
import urllibfrom urllib.request import urlopenfrom urllib.request import Requestfrom urllib.parse import urlencodeimport json url='http://127.0.0.1:8080/testpro/api/common/service'#使用 with as 打开文件,不用自己单独关闭资源with open("myFirstPythonPrj/requestDataTxt.json","r",encoding='utf-8') as f:print(f.read())#执行完read后,指针跑到了 文件最后,故后边json.load(f)会报错print("现在文件对象位置:%d" % f.tell())# 返回文件对象当前位置f.seek(0,0) # 移动文件对象至第一个字符dict_data = json.load(f)print(dict_data)data = urlencode(dict_data)#将字典类型的请求数据转变为url编码data = data.encode('ascii')#将url编码类型的请求数据转变为bytes类型headers = {'content-type': 'application/json'}req_data = Request(url,data, headers=headers)#将url和请求数据处理为一个Request对象,供urlopen调用res = Request.post(url,data, headers=headers)print(res)with urlopen(req_data) as res:res = res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为strprint(res)
使用requests实现接口调用
requests是对urllib的进一步封装,在使用上更加的方便。
需要提前安装requests
模块,使用命令:pip install requests
import json import requestsurl='http://127.0.0.1:8080/testpro/api/common/service'#使用 with as 打开文件,不用自己单独关闭资源with open("myFirstPythonPrj/requestDataTxt.json","r",encoding='utf-8') as f:header={"Content-Type":"application/json"}datas = json.load(f)get_res = requests.get(url,headers=headers,params=None)# post_res = requests.post(url,headers=headers,data=None,json=None)post_res = requests.post(url, json=datas,headers=header)print("状态码:"+ str( r.status_code ) ) #打印状态码print(post_res.text)
get_res.text得到的是str数据类型。
get_res.content得到的是Bytes类型,需要进行解码。作用和get_response.text类似。
get_res.json得到的是json数据。
如果觉得《Python-GET/POST请求(urllib.request与requests)使用Python测试POST接口(代替postman)》对你有帮助,请点赞、收藏,并留下你的观点哦!