随笔:Python+requests进行post请求之常见的三种入参
1、json格式入参,此处入参是汉字
#coding=utf-8
import requests
url = '请求地址'
header = {'content-type':'application/json'}
t = "心灵"
data = {"text":t}
#这里需要注意data和json的区别
response = requests.post(url=url,headers=header,json=data)
#对请求结果进行编码转换,转换成汉字
request = response.text.encode('utf-8').decode('unicode_escape')
#不转换返回的结果
print(response.text)
#转换后返回的结果
print(request)
返回结果:
{"value":{"2516"}}
{"value":{"情感。"}}
Process finished with exit code 0
2、csv,txt等文件格式入参
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
filename = r'D: estcloudAImxfileOLT_DEMO.csv'
file = open(filename,'rb')
url = '请求地址'
data = MultipartEncoder(
fields={
'OLT_INFO':
('OLT_DEMO.csv',
file,
'application/octet-stream')
}
)
header={}
header['content-type'] = data.content_type
response = requests.post(url=url,headers=header,data=data)
print(response.text)
3、图片格式进行base64编码加密入参
import requests
import base64
photo = r'D: estcloudAIphototestwjj.jpg'
#fp = open(photo,'rb')
with open(photo,'rb') as f:
base64_data = base64.b64encode(f.read())
s = base64_data.decode()
url = '请求url'
data = '{"imageBase64":"'+s+'"}'
header = {'Content-Type': 'application/json'}
response = requests.post(url=url,headers=header,data=data)
print(response.text)
番外:
还有常见的get请求也大同小异