带有不记名令牌的 Python 发布请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45868120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:20:56  来源:igfitidea点击:

Python post request with Bearer token

pythonrestapi

提问by Jakadinho

Im trying to make a script that post data on REST service together with Bearer token.

我正在尝试制作一个脚本,将 REST 服务上的数据与不记名令牌一起发布。

Here is working PHP example:

这是有效的 PHP 示例:

$postData = array( 'app' => 'aaaa' );

$ch = curl_init($apiUrl);
curl_setopt_array($ch, array(
    CURLOPT_HTTPHEADER, ['Authorization: Bearer '.$accessToken],
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_POSTFIELDS => json_encode($postData)
));

$response = curl_exec($ch);

Im trying to do the same with python. Here is what i got so far...

我试图用 python 做同样的事情。这是我到目前为止所得到的......

import urllib2, urllib
import json

auth_token='kbkcmbkcmbkcbc9ic9vixc9vixc9v'
hed = {'Authorization': 'Bearer ' + auth_token}
data = urllib.urlencode({'app' : 'aaaaa'})

url = 'https://api.xy.com'
req = urllib2.Request(url=url, headers=hed, data=data)
content = urllib2.urlopen(req).read()
print content

I get HTTP Error 400: Bad Request. Any help appretiated...

我收到 HTTP 错误 400:错误请求。任何帮助appretiated ...

回答by Dharmesh

import requests

auth_token='kbkcmbkcmbkcbc9ic9vixc9vixc9v'
hed = {'Authorization': 'Bearer ' + auth_token}
data = {'app' : 'aaaaa'}

url = 'https://api.xy.com'
response = requests.post(url, json=data, headers=hed)
print(response)
print(response.json())

回答by Ivan Camilito Ramirez Verdes

You can get the token from response

您可以从响应中获取令牌

request.headers['authorization']