使用Python requests调用API时出现to参数无效错误求助
解决动态加载
to参数时API返回"Invalid parameter - : to"的问题 问题根源
你的核心问题是从文件读取的号码包含不可见空白字符(比如换行符\n、回车符\r或多余空格)——虽然打印时显示正常,但实际传递给API的to参数带了这些无效字符,导致API判定参数非法。而写死参数时没有这个问题,是因为直接传入的是干净的字符串。
另外代码还存在隐藏问题:使用time.sleep()但未导入time模块,执行时会触发NameError。
解决方案
- 对读取的号码执行空白字符清理:用
str.strip()去除字符串首尾的所有空白字符(包括换行、回车、空格等)。 - 导入缺失的
time模块。 - 可选:添加号码格式校验,提前过滤不符合API要求的号码(比如必须以
+开头)。
修正后的完整代码
import requests import time # 新增:导入time模块 accesstoken = "74e41f9c-8ae6-4ebd-9568-f0c92e83bb54" authnn = "4ef2db2b-70ea-11ed-9f86-063d0d6fdfb5" def sender(number): # 关键修改:清理号码首尾的空白字符 cleaned_number = number.strip() # 可选校验:确保号码格式符合API要求 if not cleaned_number.startswith('+'): print(f"无效号码格式:{cleaned_number},需以+开头") return smstext = "hello test now#" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0', 'accessToken': accesstoken, 'Authorization': authnn } json_data = { 'content': smstext, 'contentType': 'TEXT', 'from': '+447860002234', 'to': cleaned_number, # 使用清理后的号码 } response = requests.post('https://api-sandbox.exmpl.io/v1/mms/', headers=headers, json=json_data) resp = response.text if '"acceptedTime":"' in resp: print(f"SENT OK | {cleaned_number} | {resp}") print(json_data) time.sleep(10) else: print(f"ERROR => {resp}") print(json_data) # 移除exit():避免单个号码失败就终止所有任务 if __name__ == "__main__": nums = input("NUMBERS LIST : ") with open(nums, "r") as op: # 使用with语句自动管理文件资源 for line in op: for num in line.split(): sender(num)
关键修改说明
cleaned_number = number.strip():彻底清除号码首尾的不可见空白字符,确保传递给API的是干净的有效字符串。- 新增
import time:解决time.sleep()未定义的报错问题。 - 移除
exit():避免单个号码请求失败就终止整个程序,让其他号码可以继续尝试发送。 - 使用
with open(...):自动关闭文件,避免资源泄漏问题。 - 格式校验:提前过滤不符合要求的号码,减少无效API请求。
测试建议
可以在清理号码后添加打印,直观确认清理效果:
print(f"原始号码: [{number}],清理后: [{cleaned_number}]")
内容的提问来源于stack exchange,提问作者helen marry
相关产品推荐
相关产品推荐

