get请求url
https://host:port/path?x=a&y=b
get请求参数(params)
一般在url里面的叫做params参数,用fiddler抓包后,在请求的WebForms-QueryString查看(这是向服务器提交的数据),有对应的name和value值
代码:
# coding:utf-8
import requests
s = requests.session()
url = "http://www.example.com"
par = {
"a":"1",
"b":"2",
"c":"3",
"d":"4"
}
r = s.get(url,params=par)
fiddler抓包结果
post请求参数
(1)参数可以与get请求一样放在url之后,上传后,参数在请求的WebForms-body查看
(2)不带参数
(3)放在body上传
body上传类型(四种)
(1)application/json:json格式上传,比较常用
格式:{"user":"admin","pwd":"123456"}
(2)application/x-www-form-urlencode:原生表单形式上传
格式:user=admin&pwd=123456
(3)multipart/form-data:表单形式
除了原生表单,我们经常用到的是上传文件用的表单,就是multipart/form-data这种类型的表单
一般用于文件、表单、附件上传
如下:上传图片的请求
(4)text/xml:xml形式上传
1.分析请求信息打开WebForms栏(上传图片)
2.表单格式需要用到requests_toolbelt模块转换
(1)安装 pip install requests_toolbelt
(2)使用需要导入模块 from requests_toolbelt import MultipartEncoder
(3)转换格式:m = MultipartEncoder( fields = { "xxx1":"xxx1","xxx2":"xxx2" } )
(4)传参格式:(url,data=m,headers={"Content-Type":m.content_type})
3.请求上传图片接口代码实现(需登录后再上传)
代码:
# coding:utf-8
import requests
from requests_toolbelt import MultipartEncoder
class SendImage():
def __init__(self):
self.s = requests.session()
self.headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"Origin":"http://192.168.1.9:8080"
}
def login(self, userAccount, pwd):
login_url = "http://192.168.1.9:8080/xxxxx"
data = {"userAccount": userAccount, "pwd": pwd}
body = {
"data":'%s'%data
}
r1 = self.s.post(login_url, headers=self.headers, data=body, verify=False)
print(r1.text)
def send_image(self, file_path="C://Users/PC/Desktop/20190126082136.png"):
file_url = "http://192.168.1.9:8080/xxxx?busObj=t_con_picture&size=[%22175x165%22]"
m = MultipartEncoder(
fields = {
"id": (None, "WU_FILE_0"),
"name": (None, "20190126082136.png"),
"type": (None, "image/png"),
"lastModifiedDate": (None, "Sat Jan 26 2019 08:21:39 GMT+0800 (中国标准时间)"),
"size": (None, "455502"),
"file": ("20190126082136.png", open(file_path, "rb"), "image/png")
}
)
headers = {"Content-Type":m.content_type}
r2 = self.s.post(file_url, data=m, headers=headers)
print(r2.text)
if __name__ == '__main__':
l = SendImage()
l.login("suner001", "b123456")
l.send_image()
结果:
1.请求的url将path路径与param参数分开
2.请求可能会有证书问题,在请求时最好忽略警告
r = requests.get(url,params=par,verify=False)
3.r.text 打印时出现乱码,说明返回的内容被压缩了,可以用r.content.decode("utf-8")按utf8格式输出
4.无论是get/post请求,跟在url后面的传参用params,body上传类型,json格式的传参用json,其余用data
(查看请求的数据格式,可以在请求头部Content-Type查看,如果是json会表明是json格式,同时可在json查看方式查看具体解析的内容)
5.post请求中,如果key重复,可将字典格式用列表(元组)格式去请求