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¶m2=param2_val¶m3" 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¶m2=param2_val¶m3" with urlopen(api_url) as resp: data = resp.read()
内容的提问来源于stack exchange,提问作者amitection
相关产品推荐
相关产品推荐

