用python3连oanda的模拟交易api时现HTTP错误401:未经授权,新手求教:
import urllib.parse
import urllib.request
url = 'https://api-fxpractice.oanda....'
access_token = 'a554db3a48ac8180a6996a5547ba1663-ac5947e64456cc5842a34f4ce05e4380'
account_id = 'cawa11'
values = {'accountId' :account_id}
headers = {'授权': ‘承载’+access_token}
data = urllib.parse.urlencode(values).encode("utf-8")
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
the_page = response.read()
报错:
回溯(最近一次调用最后一次):
文件“C:UserslenovoDesktopbb.py”,第 36 行,在
文件“C:Python34liburllibrequest.py”,第 161 行,在 urlopen 中
雷雷文件“C:Python34liburllibrequest.py”,第 469 行,打开
雷雷文件“C:Python34liburllibrequest.py”,第 579 行,在 http_response
雷雷文件“C:Python34liburllibrequest.py”,第 507 行,错误
雷雷文件“C:Python34liburllibrequest.py”,第 441 行,在 _call_chain 中
雷雷文件“C:Python34liburllibrequest.py”,第 587 行,位于 http_error_default
雷雷urllib.error.HTTPError:HTTP 错误 401:未经授权
雷雷
问题已解决,谢谢各位关注:
import requests
import json
instruments = 'EUR_USD'
account_id = 'cawa11'
access_token = 'a554db3a48ac8180a6996a5547ba1663-ac5947e64456cc5842a34f4ce05e4380'
params = {'instruments':instruments,'accountId':account_id}
headers = {'Authorization':'Bearer '+access_token}
r = requests.get("https://api-fxpractice.oanda.com/v1/prices",headers = headers, params=params)
price = r.json()
print(price'prices'['instrument'].replace('_','/'),':',round((price'prices'['ask']+price'prices'['bid'])/2,4))
输出:EUR/USD : 1.0905