在Python中发送URL数据Curl / Json

时间:2016-05-09 13:34:52

标签: python curl

我正在尝试使用带有url参数的python中的curl但是它返回"无",在php中使用相同参数的相同api工作正常。 这是我的python代码:

from StringIO import StringIO
import pycurl, json

apiurl = 'http://servername.com:7705'

data = json.dumps({"node": "test", "type": "get_by_field"})

c = pycurl.Curl()
c.setopt(pycurl.URL, apiurl)
c.setopt(pycurl.HTTPHEADER, ['Accept: application/json'])
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
response = c.perform()
c.close()
print response

1 个答案:

答案 0 :(得分:2)

试试这个

import StringIO
import pycurl, json

fout = StringIO.StringIO()

apiurl = 'http://servername.com:7705'

data = json.dumps({"node": "test", "type": "get_by_field"})

c = pycurl.Curl()
c.setopt(pycurl.WRITEFUNCTION, fout.write)

c.setopt(pycurl.URL, apiurl)
c.setopt(pycurl.HTTPHEADER, ['Accept: application/json'])
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.perform()
c.getinfo(pycurl.RESPONSE_CODE)
fout.getvalue()