我正在尝试使用Python请求库发出API POST请求。我正在通过Authorization
标头,但是当我尝试调试时,可以看到标头已被删除。我不知道发生了什么。
这是我的代码:
def make_post_request():
access_token = get_access_token()
bearer_token = base64.b64encode(bytes("'Bearer {}'".format(access_token)), 'utf-8')
print bearer_token
headers = {'Content-Type': 'application/json', 'Authorization': bearer_token}
data = '{"FirstName" : "Jane", "LastName" : "Smith"}'
response = requests.post('https://myserver.com/endpoint', headers=headers, data=data)
print response.request.headers
print response.text
print response.request.headers
的结果是:{'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.4.3 CPython/2.7.9 Linux/4.1.19-v7+'}
并且请求失败,并显示一条错误消息,提示'无效的会话ID'-考虑到请求标头中没有Authorization标头,这不足为奇。
令我真正困惑的是,如果我将POST请求更改为GET请求,它将通过标头!
为什么该库将删除POST请求的标头,如何使它正常工作?
使用请求库v2.4.3和Python 2.7.9
这是请求文档所说的:
Authorization headers set with headers= will be overridden if credentials are specified in .netrc, which in turn will be overridden by the auth= parameter.
Authorization headers will be removed if you get redirected off-host.
您是否在请求中被重定向?
如果是这种情况,请尝试在发布请求中使用此选项禁用重定向:
allow_redirects=False
您可以尝试在标题中使用自定义授权。
定义自定义身份验证类:
class MyAuth(requests.auth.AuthBase):
def __init__(self, bearer_token):
self.username = None
self.bearer_token = bearer_token
def __call__(self, r):
r.headers['Authorization'] = self.bearer_token
return r
然后使用它发送请求:
headers = {'Content-Type': 'application/json'}
data = '{"FirstName" : "Jane", "LastName" : "Smith"}'
response = requests.post('https://myserver.com/endpoint', headers=headers, auth=MyAuth(bearer_token), data=data)
如果可行,请接受答案。或者,如果您仍有问题,请告诉我们。希望这会有所帮助。