-2

DOWNVOTERS: leave a comment with some constructive critisism! I have no fkn clue what is wrong with this question.

How do I make a POST-request in python3?

I'm trying to fetch google plus ones for some url's the common but unofficial way through json-rpc.

I found this code but I can't get it to work:

import urllib2, json

data = '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"%s","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]' % "http://stackoverflow.com"
url = "https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ"
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()

result = json.loads(response)

print int(result[0]['result']['metadata']['globalCounts']['count'])

The docs aren't really that helpfull either. I can do the request without problems with other tools but not in python3. Any hints, please?

Filip Haglund
  • 13,919
  • 13
  • 64
  • 113
  • "I can't get it to work" - do you get errors? If so, give a full traceback. Do you get unexpected outputs? If so, what outputs, and for what inputs? – jonrsharpe Dec 28 '13 at 21:47

1 Answers1

3

If you want to do something like making a POST or other HTTP request, may I suggest the excellently written Requests library.

Try something like this:

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://URL.org", params=payload)
if r.status_code == 200:
  json = r.json()
else:
  json = None
wheaties
  • 35,646
  • 15
  • 94
  • 131