Requests03--POST方法

requests.post方法

requests.post作用

实现使用post方法发送http请求,用于向服务器提交资源

requests.post的场合

根据接口需求确定使用post方法还是其它方法
登陆一般使用post因为安全,get也能但是不安全
访问某某主页使用get
最简单的判断根据需求来判断接口请求方式

requests.post的语法形式

requests.post(url,data,json,allow_redirects,headers,auth,cookies)
参数url必须写,其它的根据实际情况选择是否要使用

requests.post的返回值

返回response对象
经常使用此对象的属性statusx_code活获得响应吗,使用此对象的text属性获得响应正文

post发送数据的类型

1)表单类型:application/x-www-form-urlencoded,默认使用的类型,这种类型会把参数变成a=1&b=2的形式
2)json类型:application/json,发送json字符串
3)data和json不能同时使用,具体类型看需求
4)multipart/form-data类型:一般用于上传文件,比如银行办理业务时,需要客户出示身份证件,银行工作人员会通过接口上传资料文件
5)xml类型(目前处于淘汰基本无用)
6)发送数据的类型以后开发人员确定,测试时看需求

requests.post(url, data)

1)模拟http的post方法发送数据,发送的数据存在请求体中
2)data表示以form表单形式发送数据,默认格式
3)data必须是字典格式:{'键':'值'}
4)data提交的数据不放在url链接里,而是放在请求正文中
params参数的数据一般放在url链接中
<1>查看实际请求的url:res.url
<2>查看请求体:res.request.body
查看请求头:res.request.headers
content-type:application/x-www-form-urlencoded,意思是post以form表单形式发送的数据

post发送表单数据

'''
post发送表单数据,查看响应正文、实际请求的url、请求头、请求体
接口地址:http://IP/apitest/login/
请求方法:post
参数:username、password
数据库表:apitest.users
响应类型:text/html
预期包含文本:用户**登录成功
'''
import requests #1、导入requests
url='http://192.168.139.129/apitest/login/'#2、指定接口地址
args={'username':'admin', 'password':'123456'} #3、指定参数
res=requests.post(url,args) #4、发送请求,获得响应结果
print(res.text) #5、查看响应结果
# print(res.request.url) #实际请求的url
# print(res.request.headers) #请求头,User-Agent表示客户端信息,Content-Type表示发送数据的类型,application/x-www-form-urlencoded表示表单类型
print(res.request.body) #请求体,username=admin&password=123456就是表单类型形式
#对比get
url='http://192.168.139.129/apitest/multi-params/'
args={'id':1,'username':'dumb'}
res=requests.get(url,args)
# print(res.text)
# print(res.request.url) #get方法的参数或数据在url之后
# print(res.request.headers) #get没有发送数据的类型
print(res.request.body) #get的请求体为空
"""
接口需求:
    接口描述:以post方式提交数据到登陆接口
    目的:使用post方法向http://192.168.139.129/apitest/ui-login/login.php发送数据
    接口地址:http://192.168.139.129/apitest/ui-login/login.php
    方法:post
    参数:username,password
    数据库表:apitest.users
    返回值:text/html类型
        登陆成功的返回:用户<u><b><font color=red>admin</font></b></u>登陆成功!
        账号或密码错误的返回:用户名或密码错误!
    写法:requests.post(url,data)
    只能使用r.text查看响应结果,不可以使用r.json()
"""
import requests
url = "http://192.168.139.129/apitest/ui-login/login.php"
data = {"username":"Dumb","password":"Dumb"}
r = requests.post(url,data=data)#正确写法
r = requests.post(url,data)#正确写法
r = requests.post(url,json=data)#错误展示
print(r.text)
上一篇:Swirles(漩涡) Court(阁) Maintenance Requests


下一篇:Requests02--Get方法