带有Bearer令牌的Python post请求

时间:2017-08-24 17:56:46

标签: python rest api

我试图创建一个脚本,将数据发布在REST服务上以及Bearer令牌。

这是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);

我试图用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

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

2 个答案:

答案 0 :(得分:15)

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())

答案 1 :(得分:0)

您可以从响应中获取令牌

request.headers['authorization']