How do I use Python's httplib to send a POST to a URL, with a dictionary of parameters?
Asked Answered
E

2

20

I just want a function that can take 2 parameters:

  • the URL to POST to
  • a dictionary of parameters

How can this be done with httplib? thanks.

Elias answered 3/3, 2010 at 9:27 Comment(1)
Please use urllib2. https://mcmap.net/q/662191/-urllib2-data-sending.Iceland
E
40

From the Python documentation:

>>> import httplib, urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
...            "Accept": "text/plain"}
>>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80")
>>> conn.request("POST", "/cgi-bin/query", params, headers)
>>> response = conn.getresponse()
>>> print response.status, response.reason
200 OK
>>> data = response.read()
>>> conn.close()
Elias answered 3/3, 2010 at 9:38 Comment(3)
Credit where credit is due: this was ripped off directly from docs.python.org/release/2.6/library/httplib.html (or 2.5.2 or earlier, it hasn't changed much over the years)Ambition
Do the params need to be in that format? can they be raw text?Ellis
Yes you can pass in raw text as params, urllib.urlencode just takes care of url encoding the string to be passed, if you print it out you will see that its just a stringLissalissak
N
11

A simpler one, using just urllib:

import urllib
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
f = urllib.urlopen("http://www.example.org/cgi-bin/query", params)
print f.read()

Found in Python docs for urllib module

No answered 1/3, 2013 at 14:44 Comment(2)
sorry, but this most probably does a HTTP GET, not a POSTCoucher
@Coucher No, it's from the POST example on that urllib page. Note that params are added with , params instead of % params.Clew

© 2022 - 2024 — McMap. All rights reserved.