0

I need to send simple JSON using POST to webserver.

Now I'm using curl and it works:

curl -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"abc":123}' http://1.2.3.4:4321/api/test

How can I do it in python?

I wrote:

import urllib2
import json
from json import JSONEncoder

jsonString= JSONEncoder().encode({ 
   "abc": 123
})
print 'JSON: ', jsonString

url = 'http://1.2.3.4:4321/api/test'
req = urllib2.Request(url, jsonString)
response = urllib2.urlopen(req)
print response.read()

But it crash:

/usr/bin/python2.7 /tmp/rest.py
JSON:  {"abc": 123}
Traceback (most recent call last):
  File "/tmp/rest.py", line 50, in <module>
    registerNewDevice()
  File "/tmp/rest.py", line 33, in registerNewDevice
    response = urllib2.urlopen(req)
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 400: Bad Request

Process finished with exit code 1
1

1 Answer 1

1

You are not passing the headers to Request You need at least specify the content-type (as you are doing when you call curl)

Would be something like this:

req = urllib2.Request(url, jsonString, {'Content-Type': 'application/json'})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.