python 发送post请求
在 Python 中发送 POST 请求有多种方式,以下是其中两种常用方法:
- 使用 requests 库发送 POST 请求:
import requests
url = 'http://example.com/api'
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, data=data)
print(response.text)
- 使用 urllib 库发送 POST 请求:
from urllib import request, parse
url = 'http://example.com/api'
data = {'key1': 'value1', 'key2': 'value2'}
data = parse.urlencode(data).encode()
req = request.Request(url, data=data)
response = request.urlopen(req)
print(response.read().decode())
在以上两种方法中,url 是请求的地址,data 是 POST 请求的数据,可以是字典或字符串。使用 requests 库可以直接传入字典,使用 urllib 库需要将数据编码为 bytes 类型。发送 POST 请求后,可以通过 response 对象获取响应内容。
原文地址: https://www.cveoy.top/t/topic/nAv 著作权归作者所有。请勿转载和采集!