我正在嘗試發送的正文:
update_request={
"id": "f07de0a44c2911ea8fb2bc764e10b970",
"user": {
"user": "3491574055045",
"timestamp": "1640049459",
"signature": "YQvl1dWkN6MrHQ8xGwEQndVo2QdPSzc6EqLJslzNjy4=",
"code": "test"
}
}
這是我現在的代碼:
url = "https://api.ordergroove.com/customer/update_customer"
headers = {
'content-type': 'application/json'
}
body = """
update_request={{
"id": "f07de0a44c2911ea8fb2bc764e10b970",
"user": {
"timestamp": "1640049459",
"signature": "YQvl1dWkN6MrHQ8xGwEQndVo2QdPSzc6EqLJslzNjy4=",
"code": "test"
}
}}
"""
#Send and print response
response = requests.post(url, data=body, headers=headers)
如果我在 Postman 中運行它,雖然它作業得很好:

uj5u.com熱心網友回復:
也許……這是一個很大的也許
url = "https://api.ordergroove.com/customer/update_customer"
data = {"update_request":{
"id": "f07de0a44c2911ea8fb2bc764e10b970",
"user": {
"timestamp": "1640049459",
"signature": "YQvl1dWkN6MrHQ8xGwEQndVo2QdPSzc6EqLJslzNjy4=",
"code": "test"
}
}
}
requests.post(url,json=data)
可能作業...
uj5u.com熱心網友回復:
在您的情況下,您的內容型別指定 JSON,這是一種常見的正文型別,因此請求通過指定 json=body 添加了一種完全不同的方式來發送 json 正文(使用 json 引數)。 Body 是另一種字典型別,然后會為您決議為字串并與請求一起發送。 x-www-form 編碼和 json 都是常見的主體型別,本質上是字典,因此它們可以經常混淆但不能互換。
data = {
"update_request":{
"id": "f07de0a44c2911ea8fb2bc764e10b970",
"user": {
"timestamp": "1640049459",
"signature": "YQvl1dWkN6MrHQ8xGwEQndVo2QdPSzc6EqLJslzNjy4=",
"code": "test"
}
}
}
response = requests.post(url,json=data)#data=body for x-www-urlencoded form data, json=body for content-type json
在這種情況下,請求將自動添加 content-type json 標頭并將字典正確地格式化為字串,而不是發送 content-type x-www-form 編碼的 content-type 標頭(如果您要放置 body=data)
您仍然可以通過傳入 json=raw_data 來為請求使用原始 json 資料,原始資料是一個字串。這是不受歡迎的,因為如果存在任何格式問題,服務器可能無法讀取您的請求正文。當您可以像前面展示的那樣傳入一個 python 字典物件時,沒有理由這樣做,并且 requests 會為您將其決議為一個字串!
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/390682.html
上一篇:根據日期列計算開始日期結束日期
