0

Possible Duplicate:
CURL alternative in Python

I'm trying to write a python snippet that returns a JSON response. With curl it works and look like this:

curl -H 'content-type: application/json' \
     -d '' http://example.com/postservice.get_notes

How could I write code in python that returns a JSON object as the curl command does?

0

1 Answer 1

2

To exactly mimic this you'll need pycurl.

import pycurl
import StringIO 

buf = StringIO.StringIO()

c = pycurl.Curl()
c.setopt(c.URL, 'http://example.com/postservice.get_notes')
c.setopt(c.WRITEFUNCTION, buf.write)
c.setopt(c.HTTPHEADER, ['Accept-Charset: UTF-8'])
c.setopt(c.POSTFIELDS, '')
c.perform()

json = buf.getvalue()
buf.close()

Note here content-type: application/json is not a valid request header. So it's not needed.

Sign up to request clarification or add additional context in comments.

2 Comments

Is this the best solution to do receive data from a web-service?
Best is a relative word. So there is no Best solution unless you give any context or criteria. The solution I provided best matches your command line implementation. Both uses the same library (curl). So they will run the same code at the back end.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.