我必须测试API的结果。我发送
Key - 'Authorization'
value - { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}
我在邮递员中获得了正确的输出,但我的代码在请求中失败
import requests
from pprint import pprint
def main():
url = "http://test.example.com/recharger-api/merchant/getPlanList?circleid=1&operatorid=1&categoryid=1"
headers = {'Authorization': { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}}
response = requests.get(url, headers = headers)
data = response.json()
pprint(data)
if __name__ == "__main__":
main()
我得到的错误:
requests.exceptions.InvalidHeader: Value for header {'Authorization': { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}} must be of type str or bytes, not <class 'dict'>
答案 0 :(得分:0)
标题几乎肯定是期待 JSON 数据。 Python字典,甚至简单地转换为字符串,与JSON不同。无论如何,requests
库不接受除标题字符串以外的任何内容。 POSTMan只处理字符串,而不是Python对象,所以你不会在那里看到问题。
明确转换它:
import json
headers = {
'Authorization': json.dumps({
"merchantIp": "13.130.189.149",
"merchantHash": "c8b71ea1ab250adfc67f90938750cd30",
"merchantName": "test"
})
}