Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 755
TIMEX Avatar asked Mar 03 '10 09:03

TIMEX


2 Answers

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()
like image 171
TIMEX Avatar answered Oct 01 '22 20:10

TIMEX


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

like image 25
Beli Avatar answered Oct 01 '22 20:10

Beli