You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python requests模块调用RestAPI登录认证失败,求助排查

问题分析与解决方法
  • 问题根源:你的curl请求通过-d发送的是JSON格式的请求体,但Python代码中使用data=login_info时,requests会将字典编码为application/x-www-form-urlencoded格式的表单数据,和你设置的Content-Type: application/json不匹配,服务器无法解析请求体,因此返回400错误。

  • 修复方法:
    推荐使用json参数替代data参数,requests会自动将字典序列化为JSON字符串,同时自动设置正确的Content-Type请求头(即使你不手动指定也可以):

    #!/bin/python3.9
    import requests
    
    site_url = 'https://myserver/login'
    login_info = {'Username': 'myuser', 'Password': 'mypassword', 'InactivityTimeout': 1}
    site_headers = {'accept': 'application/json'}
    sess = requests.session()
    login_resp = sess.post(site_url, json=login_info, headers=site_headers, verify=False)
    print(login_resp)
    print(login_resp.json())  # 可查看返回的认证结果JSON
    

    也可以手动将字典转为JSON字符串后用data参数发送,需要导入json模块:

    #!/bin/python3.9
    import requests
    import json
    
    site_url = 'https://myserver/login'
    login_info = {'Username': 'myuser', 'Password': 'mypassword', 'InactivityTimeout': 1}
    site_headers = {'accept': 'application/json', 'Content-Type': 'application/json'}
    sess = requests.session()
    login_resp = sess.post(site_url, data=json.dumps(login_info), headers=site_headers, verify=False)
    print(login_resp)
    

内容的提问来源于stack exchange,提问作者luckiblue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 16:33:17