针对 Ajax 的 POST 请求,如何用 Python 实现?
原网页中的动作为:
value = 0
$('input[name=value]').val(value);
$.post('/test/', $('form.test').serialize())
这种动作; $('form.test').serialize()这个打印出来是 "testid={}&testvalue={}&tocken={}"这种类型的
我用 python 做:
headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)',
'Cookie': 'uuid=123456;',
}
params = “testid={}&testvalue={}&token={}”.format(testid, testvalue, token)
resp = requests.post(url=url, data=params, headers=headers)
print(resp)
每次 response 返回的都是状态码 400,参数错误,我修改了 data 的格式为 json,字典,str 等参数格式,都不行,找不到解决的方向了,请问有人知道解决的方法吗?
针对 Ajax 的 POST 请求,如何用 Python 实现?
3 回复
import requests
import json
# 基础POST请求
def simple_post():
url = 'https://httpbin.org/post'
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, data=data)
print(f"状态码: {response.status_code}")
print(f"响应内容: {response.text}")
# 发送JSON数据
def post_json():
url = 'https://httpbin.org/post'
json_data = {
'name': '张三',
'age': 25,
'skills': ['Python', 'JavaScript']
}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, json=json_data, headers=headers)
print(f"状态码: {response.status_code}")
print(f"JSON响应: {response.json()}")
# 带认证的请求
def post_with_auth():
url = 'https://httpbin.org/post'
data = {'message': 'secret data'}
# 基本认证
auth = ('username', 'password')
# 或使用Bearer Token
headers = {'Authorization': 'Bearer your_token_here'}
response = requests.post(url, data=data, auth=auth, headers=headers)
print(response.status_code)
# 处理文件上传
def post_file():
url = 'https://httpbin.org/post'
files = {'file': open('example.txt', 'rb')}
data = {'description': '这是一个测试文件'}
response = requests.post(url, files=files, data=data)
print(response.json())
# 异步请求(使用aiohttp)
import aiohttp
import asyncio
async def async_post():
url = 'https://httpbin.org/post'
data = {'async': 'true'}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=data) as response:
result = await response.json()
print(f"异步响应: {result}")
# 错误处理
def post_with_error_handling():
url = 'https://httpbin.org/post'
try:
response = requests.post(url, timeout=5)
response.raise_for_status() # 如果状态码不是200,抛出异常
# 确保响应是有效的JSON
if 'application/json' in response.headers.get('Content-Type', ''):
return response.json()
else:
return response.text
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.HTTPError as err:
print(f"HTTP错误: {err}")
except requests.exceptions.RequestException as err:
print(f"请求异常: {err}")
except json.JSONDecodeError:
print("响应不是有效的JSON")
# 使用示例
if __name__ == '__main__':
# 基础用法
simple_post()
# JSON请求
post_json()
# 错误处理示例
result = post_with_error_handling()
# 运行异步请求
# asyncio.run(async_post())
核心要点:
- 使用
requests库是最简单直接的方式 - 根据API要求选择
data=(表单数据)或json=(JSON数据) - 设置正确的
Content-Type请求头 - 添加必要的认证信息(auth参数或Authorization头)
- 做好异常处理,特别是网络请求可能失败的情况
建议: 用requests库就行,记得处理异常。


