當創建的請求,你應該:
- 提供
Content-Type
頭
- 在匹配
Content-Type
頭
- 確保應用格式提供數據支持的格式
兩個curl
和python
例子給你發送請求Content-Type: application/x-www-form-urlencoded
,默認一個。區別在於curl
傳遞字符串和python
傳遞數組。
讓我們比較curl
和requests
,什麼是真正貼:
捲曲
$ curl localhost -X POST -d "{\"action\": \"deckNames\", \"version\": 5}"
頁眉:
Host: localhost
User-Agent: curl/7.52.1
Accept: */*
Content-Length: 37
Content-Type: application/x-www-form-urlencoded
發佈數據:
[
'{"action": "deckNames", "version": 5}'
]
的Python
import requests
r = requests.post("http://127.0.0.1", data={'action': 'guiAddCards', 'version': 5})
print(r.text)
頁眉:
Host: 127.0.0.1
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.10.0
Content-Length: 28
Content-Type: application/x-www-form-urlencoded
發佈數據:
[
'action' -> 'guiAddCards',
'version' -> '5',
]
正如你所看到的,不正確後的數據格式傷了你的應用程序。
可以肯定的,那發佈JSON數據將得到妥善的應用程序讀取你應該做出這樣的請求:
捲曲
$ curl localhost:8765 -H 'Content-Type: application/json' -d '{"action": "deckNames", "version": 5}'
的Python
import requests
r = requests.post("http://127.0.0.1:8765", json={'action': 'guiAddCards', 'version': 5})
print(r.text)
「不幸」是什麼意思?想必你會遇到某種錯誤。什麼是服務器返回? –
[使用Python請求發佈JSON]的可能重複(https://stackoverflow.com/questions/9733638/post-json-using-python-requests) –
您能更詳細地瞭解您所面臨的具體錯誤或問題嗎?你應該能夠找到大量的python提出請求的例子。 – csmckelvey