如何将Header中的dict作为值发送给密钥'授权'在python请求?

时间:2017-11-16 10:11:44

标签: python python-3.x python-requests

我必须测试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'>

1 个答案:

答案 0 :(得分:0)

标题几乎肯定是期待 JSON 数据。 Python字典,甚至简单地转换为字符串,与JSON不同。无论如何,requests库不接受除标题字符串以外的任何内容。 POSTMan只处理字符串,而不是Python对象,所以你不会在那里看到问题。

明确转换它:

import json

headers = {
    'Authorization': json.dumps({
        "merchantIp": "13.130.189.149",
        "merchantHash": "c8b71ea1ab250adfc67f90938750cd30",
        "merchantName": "test"
    })
}