如何发布http请求而不是使用cURL?
我正在使用anki-connect与Anki(一种间隔重复软件)进行通信。
在readme.md中,它使用以下命令获取套牌名称。如何发布http请求而不是使用cURL?
curl localhost:8765 -X POST -d "{\"action\": \"deckNames\", \"version\": 5}"
它适用于我的Windows系统。
如何使用python而不是cURL?
我试过这个,但没有运气。
import requests
r = requests.post("http://127.0.0.1:8765", data={'action': 'guiAddCards', 'version': 5})
print(r.text)
我已经尝试过下面的挖掘后,这个工程。
任何人都可以分享原因。谢谢。
import requests
import json
#r = requests.post("http://127.0.0.1:8765", data={'action': 'guiAddCards', 'version': 5})
r = requests.post('http://localhost:8765', data=json.dumps({'action': 'guiAddCards', 'version': 5}))
print(r.text)
当创建的请求,你应该:
- 提供
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)
这是对user2444791答案的回复。我不能评论,因为我没有评论的声誉(我是新的,请原谅一个礼仪的臀位!)
没有确切的错误信息,很难确定,但...
查看Anki Connect API,它预计它的POST-ed数据是包含JSON对象的单个字符串,而不是与该JSON对象相同的键/值字典。
每个请求都包含一个JSON编码的对象,其中包含一个操作,一个版本和一组上下文参数。
他们的示例代码(在JavaScript):xhr.send(JSON.stringify({action, version, params}));
这可能是因为在错误的格式发送您的数据一样简单。在第一个示例中,您正在发送已经解析了键/值对的字典。在第二个例子中,你发送一个字符串让他们解析。
“不幸”是什么意思?想必你会遇到某种错误。什么是服务器返回? –
[使用Python请求发布JSON]的可能重复(https://stackoverflow.com/questions/9733638/post-json-using-python-requests) –
您能更详细地了解您所面临的具体错误或问题吗?你应该能够找到大量的python提出请求的例子。 – csmckelvey