Reputation: 3685
I have a server running at :
http://localhost:3000/appleconnect
which will accept post calls. So I have written the python code for making http request, but that doesn't work:
import httplib, urllib, json
params = json.load("{'op' : 'sign'}")
headers = {"Content-type": "application/json",
"Accept": "text/plain"}
conn = httplib.HTTPConnection("localhost:3000")
conn.request("POST", "/appleconnect",
params, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
conn.close()
The above is not working. It gives me the error like:
Traceback (most recent call last):
File "post.py", line 2, in <module>
params = json.load("{'op' : 'sign'}")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 286, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
where I'm making the mistake?
Upvotes: 0
Views: 232
Reputation: 599450
json.load
is for files or file-like objects. For a plain dict, you need json.loads
.
Edit
Your string is not valid JSON: for that you need double quotes, not single ones.
But I do not understand why you are doing this at all. It is the wrong way round: loads
converts a JSON string to Python objects, but conn.request
expects a string in the first place. I suspect you wanted to start with a Python dict, convert it to JSON, and then pass that to the request:
params = json.dumps({'op' : 'sign'})
Upvotes: 1
Reputation: 4912
You need to use json.loads
instead of json.load
.
As for the second error, you have to make sure your string is a json object first. Try this code:
import httplib, urllib, json
jsonObject = json.dumps("{'op' : 'sign'}")
params = json.loads(jsonObject)
...
Upvotes: 1