如何发布http请求而不是使用cURL?

时间:2017-10-16 14:00:18

标签: python curl

我正在使用anki-connect与间距重复软件Anki进行通信 在readme.md中,它使用以下命令获取卡组名称。

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)

3 个答案:

答案 0 :(得分:1)

创建请求时,您应该:

  • 提供Content-Type标题
  • 以匹配Content-Type标题
  • 的格式提供数据
  • 确保应用程序支持格式

您提供的curlpython示例都会向Content-Type: application/x-www-form-urlencoded发送请求,默认值为{1}。差异是curl传递字符串,python传递数组。

让我们比较curlrequests以及真正发布的内容:

<强>卷曲

$ 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)

答案 1 :(得分:0)

我在挖掘之后尝试过这种方法 任何人都可以分享原因。感谢。

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)

答案 2 :(得分:0)

这是对user2444791答案的回复。我无法回复评论,因为我没有评论的声誉(我是新的,请原谅礼仪的臀位!)

如果没有确切的错误消息,很难确定,但是......

查看Anki Connect API,它希望其POST-ed数据是一个包含JSON对象的字符串,而不是与该JSON对象等效的键/值字典。

  

每个请求都包含一个JSON编码的对象,其中包含一个动作,一个版本和一组上下文参数。

他们的示例代码(在Javascript中):xhr.send(JSON.stringify({action, version, params}));

可能就像以错误的格式发送数据一样简单。在第一个示例中,您将发送一个包含已解析的键/值对的字典。在第二个示例中,您将发送一个字符串供他们解析。