接口基本信息
接口地址:http://127.0.0.1:8080/testpro/api/common/service
调用方式:POST
参数:JSON格式字符串,放到独立的.json文件中
返回:调用码返回200
且,返回内容有效,则验证成功
代码示例
使用urllib.request调用接口
urlopen()只能用于一些简单的资源请求
# 爬百度数据
from urllib import request
response = request.urlopen("http://www.baidu.com")
fi = open("my_baidu.txt","w")
page = fi.write(str(response.read()))
fi.close()//必须要关闭资源
#处理get请求,不传data,则为get请求
import urllib
from urllib.request import urlopen
from urllib.parse import urlencode
url='http://www.xxx.com/login'
data={"username":"admin","password":123456}
req_data=urlencode(data)#将字典类型的请求数据转变为url编码
res=urlopen(url+'?'+req_data)#通过urlopen方法访问拼接好的url
res=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为str
print(res)
#处理post请求,如果传了data,则为post请求
import urllib
from urllib.request import Request
from urllib.parse import urlencode
url='http://www.xxx.com/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格式为str
print(res)
示例二 :
import urllib
from urllib.request import urlopen
from urllib.request import Request
from urllib.parse import urlencode
import 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格式为str
print(res)
使用requests实现接口调用
requests是对urllib的进一步封装,在使用上更加的方便。
需要提前安装requests
模块,使用命令:pip install requests
import json
import requests
url='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数据。