我有这个有效的卷曲,它返回这个
curl -X POST \
https://login.smoobu.com/booking/checkApartmentAvailability \
-H 'Api-Key: xxxxx' \
-H 'cache-control: no-cache' \
-d '{
"arrivalDate" : "2018-04-01",
"departureDate": "2019-12-03",
"apartments": [126936, 127858, 126937],
"customerId": 38484
}'
它返回这个
{
"availableApartments": [
127858
],
"prices": [],
"errorMessages": {
"126936": {
"errorCode": 405,
"message": "The chosen day of departure is not available.",
"departureDays": [
"Sa"
]
},
"126937": {
"errorCode": 405,
"message": "The chosen day of departure is not available.",
"departureDays": [
"Sa"
]
}
}
}
我像这样用python重写了它
In [1]: import requests
In [2]: headers = {'Api-Key': 'xxxx', 'cache-control': 'no-cache'}
In [8]: payload = {
...: "arrivalDate" : "2018-04-01",
...: "departureDate": "2019-12-03",
...: "apartments": [126936, 127858, 126937],
...: "customerId": 38484
...: }
In [4]: r = requests.post("https://login.smoobu.com/booking/checkApartmentAvailability", data=payload, headers=headers)
In [5]: r
Out[5]: <Response [400]>
In [13]: r.content
Out[13]: b'{"title":"Error occurred","detail":"json is invalid"}'
我得到了无效json的响应,但我不确定为什么会这样,因为我知道它的工作方式是将字典变成json请求。
最佳答案
要发送JSON
,应使用json
参数:
r = requests.post("https://login.smoobu.com/booking/checkApartmentAvailability", json=payload, headers=headers)
如docs中所述:
r = requests.post(url, data=json.dumps(payload))
r = requests.post(url, json=payload)
除了自己编码dict外,您还可以使用json参数(在2.4.2版中添加)直接传递dict,它将自动进行编码