使用requests.post请求返回400错误,如何在发送前打印构建的请求对象?
可行,两种方法实现请求内容预打印
方法一:手动构建PreparedRequest(推荐,精准匹配你要的输出格式)
requests支持先构建请求对象再发送,能在发送前完整查看请求的所有细节,示例代码如下:
import requests from requests.auth import HTTPBasicAuth import json # 替换成你的实际参数 accessTokenUrl = "https://test-lm.lb.com/token" clientId = "your_client_id" clientSecret = "your_client_secret" body = {"grant_type": "client_credentials", "scope": "test-admin"} # 创建会话和基础请求对象 session = requests.Session() raw_request = requests.Request( method='POST', url=accessTokenUrl, json=body, auth=HTTPBasicAuth(clientId, clientSecret) ) # 准备请求(自动处理认证头、Content-Type、内容长度等) prepared_req = session.prepare_request(raw_request) # 按需求格式打印请求头 print("Request Headers") for header_name, header_value in prepared_req.headers.items(): print(f"{header_name}: {header_value}") # 打印请求体 print("\nRequest Body") if prepared_req.body: # 因为用了json参数,解析成字典输出更美观 try: parsed_body = json.loads(prepared_req.body) for key, val in parsed_body.items(): print(f"{key}: {repr(val)}") except json.JSONDecodeError: # 非JSON格式直接打印原始内容 print(prepared_req.body)
方法二:开启requests调试日志
通过配置日志,能自动输出请求和响应的完整细节,适合快速排查问题:
import requests import logging from requests.auth import HTTPBasicAuth # 配置日志输出请求全量细节 logging.basicConfig(level=logging.DEBUG) urllib3_log = logging.getLogger("requests.packages.urllib3") urllib3_log.setLevel(logging.DEBUG) urllib3_log.propagate = True # 发送请求,日志会自动打印完整请求内容 accessTokenUrl = "https://test-lm.lb.com/token" clientId = "your_client_id" clientSecret = "your_client_secret" body = {"grant_type": "client_credentials", "scope": "test-admin"} requests.post( url=accessTokenUrl, json=body, auth=HTTPBasicAuth(clientId, clientSecret) )
额外提示:你的400错误可能和请求格式不匹配有关
你给出的示例请求头是application/x-www-form-urlencoded,但当前代码用json=body会把请求头设为application/json。如果服务器期望表单格式,把json=body改成data=body就能匹配示例里的请求格式,大概率能解决400错误。
内容的提问来源于stack exchange,提问作者Matthew
相关产品推荐
相关产品推荐

