当创建的请求,你应该:
- 提供
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