如何使用 Python 的 httplib 将 POST 发送到带有参数字典的 URL? [英] How do I use Python's httplib to send a POST to a URL, with a dictionary of parameters?
本文介绍了如何使用 Python 的 httplib 将 POST 发送到带有参数字典的 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想要一个可以接受 2 个参数的函数:
- 要发布到的 URL
- 参数字典
如何用 httplib 做到这一点?谢谢.
解决方案
来自 Python 文档:
<预><代码>>>>导入 httplib、urllib>>>params = urllib.urlencode({'垃圾邮件':1,'鸡蛋':2,'培根':0})>>>headers = {"Content-type": "application/x-www-form-urlencoded",...接受":文本/普通"}>>>conn = httplib.HTTPConnection("musi-cal.mojam.com:80")>>>conn.request("POST", "/cgi-bin/query", params, headers)>>>响应 = conn.getresponse()>>>打印 response.status, response.reason200 正常>>>数据 = response.read()>>>conn.close()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.
解决方案
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()
这篇关于如何使用 Python 的 httplib 将 POST 发送到带有参数字典的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文