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.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

2 Answers2

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()
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • 29
    Credit where credit is due: this was ripped off directly from http://docs.python.org/release/2.6/library/httplib.html (or 2.5.2 or earlier, it hasn't changed much over the years) – dland Feb 06 '12 at 14:40
  • Do the params need to be in that format? can they be raw text? – Usman Ismail Feb 13 '13 at 14:55
  • 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 string – Ole Apr 29 '13 at 09:15
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

Beli
  • 594
  • 5
  • 16