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

Python Requests库是否支持调用含无值查询参数的API?

带无值查询参数的API调用方案
  • 直接使用Python Requests库即可调用该API
    直接将完整URL传递给requests.get()方法,Requests会原样发送请求,不会修改URL中的查询参数部分。示例代码:

    import requests
    
    api_url = "https://example.com/abc/JSONInterface.jsp?param1=param1_val&param2=param2_val&param3"
    resp = requests.get(api_url)
    # 后续处理响应内容
    
  • 若需通过参数字典构造请求(避免直接拼接URL)
    默认情况下,Requests使用params字典时会将无值参数格式化为param3=,不符合需求。此时可以手动构造查询字符串:

    import requests
    from urllib.parse import urlencode, urlunparse
    
    base_components = ('https', 'example.com', '/abc/JSONInterface.jsp', '', '', '')
    params = {
        'param1': 'param1_val',
        'param2': 'param2_val',
        'param3': ''
    }
    # 生成查询字符串并修正无值参数格式
    query_str = urlencode(params).replace('param3=', 'param3')
    full_url = urlunparse(base_components[:4] + (query_str,) + base_components[5:])
    
    resp = requests.get(full_url)
    
  • 替代方案:使用标准库urllib.request
    如果你担心Requests的参数处理逻辑,Python内置的urllib.request也能原样发送该URL:

    from urllib.request import urlopen
    
    api_url = "https://example.com/abc/JSONInterface.jsp?param1=param1_val&param2=param2_val&param3"
    with urlopen(api_url) as resp:
        data = resp.read()
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:18:15