import requests
if __name__ == '__main__':
# 表单数据是字典形式
r1 = requests.post('http://httpbin.org/post', data={'key1': 'value1', 'key2': 'value2'})
# 表单数据是字典形式, 一个键对应对个值
r2 = requests.post('http://httpbin.org/post', data={'key1': ['value1', 'value2']})
# 表单数据是元组列表形式, key可以相同,等价于用'key1': ['value1', 'value2']
r3 = requests.post('http://httpbin.org/post', data=(('key1', 'value1'), ('key1', 'value2')))
print('r1:', r1.text)
print('r2:', r2.text)
print('r3:', r3.text)
输出入下:
import requests
if __name__ == '__main__':
payload = {'some': 'data'}
r = requests.post('https://api.github.com/some/endpoint', json=payload)
# 或者如下写法json.dumps(payload)将数据转换为字符串
# r = requests.post('https://api.github.com/some/endpoint', data=json.dumps(payload))
import requests
import os
if __name__ == '__main__':
# 文件的打开方式需要为rb
r1 = requests.post('http://httpbin.org/post', files={'file': open(os.path.join(os.getcwd(), '111.txt'), 'rb')})
# 上传文件,并指定文件名称
r2 = requests.post('http://httpbin.org/post', files={'file': ('111.txt', open(os.path.join(os.getcwd(), '111.txt'), 'rb'))})
# 通过文件对象上传字符串
r3 = requests.post('http://httpbin.org/post', files={'file': ('111.txt', 'hahahahaha')})
print('r1:', r1.text)
print('r2:', r2.text)
print('r3:', r3.text)
输出入下: