构建含Base64文件、JSON数据、认证及Action Header的POST请求遇403错误求修复
问题分析与修复方案
你的代码存在几处关键问题,导致请求返回403或无法被服务端正确处理,以下是具体修改点:
1. Base64编码结果的错误引用与类型问题
- 你将文件编码后存入了变量
string,但构造请求数据时错误使用了未定义的file变量,需替换为string。 base64.b64encode()返回的是字节类型,直接放入JSON会序列化失败,必须调用.decode('utf-8')转换为字符串格式。
2. 无效的请求URL
url = 'web.site'不是完整的HTTP/HTTPS请求地址,必须使用包含协议(http/https)的完整URL,比如https://web.site/api/create-order。
3. 潜在的认证方式检查
如果服务端不支持Basic Auth(即auth=(username, password)这种方式),需要将用户名和密码直接加入JSON请求体的data字典中。
修复后的完整代码
import requests import base64 # 替换为服务端提供的完整请求地址 url = 'https://web.site/api/your-target-endpoint' username = 'user123' password = 'pw123' city = 'London' countrycode = 'GB' with open("file.pdf", "rb") as pdf_file: # 将字节类型的Base64编码结果转为字符串 file_base64 = base64.b64encode(pdf_file.read()).decode('utf-8') headers = {'action':'createOrder'} # 若服务端要求用户名密码在请求体中,添加对应的字段即可 data = { 'city': city, 'countrycode': countrycode, 'file': file_base64 } r = requests.post(url, auth=(username, password), headers=headers, json=data) # 打印响应信息用于调试 print(f"状态码: {r.status_code}") print(f"响应内容: {r.text}")
内容的提问来源于stack exchange,提问作者OneNewBee
相关产品推荐
相关产品推荐

