gpt4 book ai didi

python - 使用 POST 和 urllib2 访问 Web API

转载 作者:太空狗 更新时间:2023-10-29 22:11:57 26 4
gpt4 key购买 nike

我正在尝试使用 POST 技术访问 Web API。我能够使用 GET 技术访问它,但 API 所有者告诉我某些功能仅适用于 POST。不幸的是,我似乎无法让 POST 工作。

以下是 GET 的作用:

API_URL = "http://example.com/api/"

def call_api(method, **kwargs):
url = API_URL + method
if kwargs:
url += '?' + urllib.urlencode(kwargs)
req = urllib2.Request(url)
auth = 'Basic ' + base64.urlsafe_b64encode("%s:%s" % (USER, PASS))
req.add_header('Authorization', auth)
return urllib2.urlopen(req)

以下是不适用于 POST 的内容(导致 HTTP 400 错误):

API_URL = "http://example.com/api/"

def call_api(method, **kwargs):
url = API_URL + method
data=''
if kwargs:
data=urllib.urlencode(kwargs)
req = urllib2.Request(url, data)
auth = 'Basic ' + base64.urlsafe_b64encode("%s:%s" % (USER, PASS))
req.add_header('Authorization', auth)
return urllib2.urlopen(req)

有没有人突然发现 POST 代码中存在固有错误?我以前从未进行过 POST 调用,但我读过的所有内容似乎都表明我的代码是合理的。如果我使用的是 POST,是否有一些不同的方法可以为授权执行 add_header 操作?

最佳答案

使用 urllib2,您需要将数据添加到 POST 主体:

def call_api(method, **kwargs):
url = API_URL + method
req = urllib2.Request(url)

if kwargs:
req.add_data(urllib.urlencode(kwargs))

auth = 'Basic ' + base64.urlsafe_b64encode("%s:%s" % (USER, PASS))
req.add_header('Authorization', auth)

# req.get_method() -> 'POST'

return urllib2.urlopen(req)

关于python - 使用 POST 和 urllib2 访问 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4195325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com