GET请求, url存放访问的路径,params请求的参数,headers存放请求头
调用的库函数requests.get(url, params=params,headers=headers) 这个方法会有返回,可以使用一个变量来接收响应体。
这里使用with as 接收参数对响应体做了操作
import requests
# 目标URL
url = 'http://localhost:8080/las/las/report/export/biLiabilityDue'
# 要携带的参数
params = {'companyName': '公司', 'companyCode': '000F', 'periodName': '2019-01', 'reportType': 'L'}
headers = {
'cookie': 'cookie',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'
}
# 发送GET请求,并将参数添加到URL中
local_filename=r'C:\Users\Desktop\downloaded_file.xlsx'
with requests.get(url, params=params,headers=headers) as r:
r.raise_for_status() # 如果响应状态码不是200,则引发HTTPError异常
# 确保文件模式为二进制
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
# 如果chunk存在,则写入文件
if chunk:
f.write(chunk)
# 文件现在已经被保存到local_filename指定的路径
print(f'File saved to {local_filename}')
POST请求,可以传入两种类型的参数,见格式或者普通格式
import requests
import json
# 目标URL
url = 'http://localhost:8090/prod/csc-mgr/api/v1/workOrder/getPendingWorkOrderList'
# POST请求的数据
data = {"isComplain":"","isOvertime":"","isRemind":"","isStar":"","submitUserName":"","typeCode":"","fromWay":"","content":"","systemSource":"ipa","moduleCode":"","childModuleCode":"","createdTimeStart":"","createdTimeEnd":"","createdTimeRange":[],"pageSize":20,"pageNum":1,"totalCount":3,"transferOrderOrNot":"","feedbackUserName":""}
# 携带的cookie或者令牌
headers = {
'authorization': 'Bearer eyJhbGciOiJIUBiI8VEvMC-p_DJ7tdD_at8IY'
}
# 如果API期望JSON格式的POST数据,使用json=data
response = requests.post(url, json=data, headers=headers)
# 响应状态码
print(response.status_code)
# 打印响应内容
print(response.text)
# 解析JSON(这里不需要检查response.json(),因为response.json()总是返回一个字典或列表)
if response.headers.get('Content-Type') == 'application/json':
print(json.dumps(response.json(), indent=4))
else:
print(response.text) # 对于非JSON响应,直接打印文本
if response.headers.get('Content-Type') == 'application/json':
print(json.dumps(response.json(), indent=4))
这一部分是格式化返回参数