读取TXT文件数据调用API遇400错误,请求技术排查
问题分析与解决方案
核心问题
- 字典变量解析错误:你代码中
data的写法完全错误——用f"nickname":"{creds}"这种格式会把{creds}当成字面量字符串而非变量,导致服务器收到的是"{creds}"而非实际读取的用户名,这就是Wireshark抓包显示nickname=%7Bcreds%7D(%7B/%7D是{/}的URL编码)、服务器提示字段为空的直接原因。 - 请求头设置错误:强行把
Content-Type设为text/plain完全不符合请求体格式——当你用data参数传字典时,requests默认会把数据编码为application/x-www-form-urlencoded格式,错误的头会让服务器无法解析请求内容。
修正代码(两种常见场景)
场景1:API接受表单格式(application/x-www-form-urlencoded)
import requests with open('./user.txt', 'r') as f: creds = f.read().strip() # 去除文件中可能存在的换行/空格 print(f"Current User: {creds}") url = 'http://example.com/api' # 直接用普通字典传递键值对,无需f-string包裹 data = { "nickname": creds, "password": creds, "email": "", "referral": "null" } # 删掉错误的Content-Type头,requests会自动设置正确的请求头 response = requests.post(url, data=data) # 打印响应信息方便排查 print(response.status_code) print(response.text)
场景2:API接受JSON格式(更常用)
如果API要求JSON格式的请求体,直接用json参数传递数据即可,requests会自动设置Content-Type: application/json:
import requests with open('./user.txt', 'r') as f: creds = f.read().strip() print(f"Current User: {creds}") url = 'http://example.com/api' payload = { "nickname": creds, "password": creds, "email": "", "referral": "null" } # 使用json参数替代data参数 response = requests.post(url, json=payload) print(response.status_code) print(response.text)
额外提示
读取文件时加strip()是为了避免txt文件末尾的换行符、空格等多余字符被当成用户名的一部分,这也是导致服务器识别字段为空的常见隐性问题。
内容的提问来源于stack exchange,提问作者Hyperninja303
相关产品推荐
相关产品推荐

