python使用requests模拟multipart/form-data请求
模拟multipart/form-data请求,会遇到:Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7RgPwjW5Gf1JZ9SX的情况。
以下使用库 requests_toolbelt 实现
安装
pip install requests_toolbelt
下面是简单的请求示例:
import os
import random
import string
import requests
from requests_toolbelt import MultipartEncoder
# 请求地址
mUrl = "http://xxxx.com"
# 传入字段
fields = {
'username':"username",
'password':"password",
'type':"account",
}
# 添加自定义分割线
boundary = '----WebKitFormBoundary' + ''.join(random.sample(string.ascii_letters + string.digits, 16))
form_data = MultipartEncoder(fields,boundary=boundary)
header = {
'Content-Type':form_data.content_type,
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br, zstd',
'Accept-Language':'zh-CN,zh;q=0.9',
'Connection': 'keep-alive',
}
print("headers = \n",header)
#print("form_data = \n",form_data.read().decode('utf-8'))
respon = requests.post(url=mUrl,data=form_data,headers=header)
if respon :
response.encoding = 'utf-8'
print("===================================")
print(response.text)
pass
else:
print("未获取信息====================")
pass
注:form_data.read().decode('utf-8') 只能调用一次,正常使用时不要调用哦!!!!!
打印显示如下:
headers =
{'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryMW7YzGio0URgt5rk', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br, zstd', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive'}
form_data =
------WebKitFormBoundaryMW7YzGio0URgt5rk
Content-Disposition: form-data; name="username"
username
------WebKitFormBoundaryMW7YzGio0URgt5rk
Content-Disposition: form-data; name="password"
password
------WebKitFormBoundaryMW7YzGio0URgt5rk
Content-Disposition: form-data; name="type"
account
------WebKitFormBoundaryMW7YzGio0URgt5rk--
网友评论