自定义pycurl调用

Custom pycurl call

我正在尝试实现推送通知。我可以通过此调用触发通知,我需要从 python:

curl -X POST -H "Content-Type: application/json" -H "X-Thunder-Secret-Key: secret2" --data-ascii "\"Hello World\"" http://localhost:8001/api/1.0.0/key2/channels/mychannel/

这在命令行中工作正常。

首先我尝试使用子进程,但它给了我这个奇怪的错误:

curl: (1) Protocol "http not supported or disabled in libcurl

所以我放弃了,我正在尝试使用 pycurl。但问题是我不知道如何使用 -X 和 --data-ascii 选项。

import pycurl
c = pycurl.Curl()
c.setopt(c.HTTPHEADER, ['Content-Type: application/json','X-Thunder-Secret-Key: secret2'])
c.setopt(c.URL, 'http://localhost:8001/api/1.0.0/key2/channels/mychannel/')
c.perform()
print("Done")

那么如何添加 -X 选项以及如何发送带有请求的文本消息?

如果需要HTTP POST request, see documentation example.

我认为这样的事情应该可行(我用过 python 2):

import pycurl    

c = pycurl.Curl()

postfields = '"Hello World"'
c.setopt(c.URL, 'http://pycurl.sourceforge.net/tests/testpostvars.php')
c.setopt(c.HTTPHEADER, ['Content-Type: application/json','X-Thunder-Secret-Key: secret2'])
# Here we set data for POST request
c.setopt(c.POSTFIELDS, postfields)

c.perform()
c.close()

此代码生成以下 HTTP 数据包:

POST /tests/testpostvars.php HTTP/1.1
User-Agent: PycURL/7.19.5.1 libcurl/7.37.1 SecureTransport zlib/1.2.5
Host: pycurl.sourceforge.net
Accept: */*
Content-Type: application/json
X-Thunder-Secret-Key: secret2
Content-Length: 13

"Hello World"