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

旧城冷巷雨未停 提交于 2019-12-05 09:57:38

问题


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.


回答1:


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()



回答2:


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



来源:https://stackoverflow.com/questions/2370003/how-do-i-use-pythons-httplib-to-send-a-post-to-a-url-with-a-dictionary-of-para

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!