python requests post请求参数为多重字典的情况

2018-08-01  本文已影响0人  gz_tester

举例说明

请求参数为:

{
    "a": 1,
    "b": {
        "b1": 2,
        "b2": {
            "b2-1": 3,
            "b2-2": 4
        }
    },
    "c": 5
}

第一种解决办法:

声明header的Content-Type为:application/json

import requests

headers = {'Content-Type': 'application/json'}
url = "https://gz_tester.test.com/save-basicinfo"
data = {
    "a": 1,
    "b": {
        "b1": 2,
        "b2": {
            "b2-1": 3,
            "b2-2": 4
        }
    },
    "c": 5
}
r = requests.post(url=url, json=data, headers=headers)
print(r.status_code)

运行结果如图:


image.png

第二种解决办法:

声明header的Content-Type为:application/json,
把data转换为json的字符串格式

import requests
import json

headers = {'Content-Type': 'application/json'}
url = "https://gz_tester.test.com/save-basicinfo"
data = {
    "a": 1,
    "b": {
        "b1": 2,
        "b2": {
            "b2-1": 3,
            "b2-2": 4
        }
    },
    "c": 5
}
r = requests.post(url=url, data=json.dumps(data), headers=headers)
print(r.status_code)

运行结果如图:


image.png
上一篇 下一篇

猜你喜欢

热点阅读