我究竟如何使用参数发送HTTP Post Request(使用httplib)?
我理解课程。我只是不明白如何发送参数。
请提供完整的示例脚本。
答案 0 :(得分:3)
这是一个示例会话,显示如何POST请求:
>>> import httplib, urllib
>>> params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
... "Accept": "text/plain"}
>>> conn = httplib.HTTPConnection("bugs.python.org")
>>> conn.request("POST", "", params, headers)
>>> response = conn.getresponse()
>>> print response.status, response.reason
302 Found
>>> data = response.read()
>>> data
'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
>>> conn.close()a
来自here
答案 1 :(得分:1)
这是一个简短的脚本,我用它来完成你所要求的(如果你将params作为字典或关联数组传递,这将有效):
#!/usr/bin/python
import urllib
import urllib2
urlencode = urllib.urlencode
urlopen = urllib2.urlopen
Request = urllib2.Request
def request (url, params):
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Accept': '*/*'
}
try:
data = urlencode(params)
req = Request(url, data, headers)
response = urlopen(req)
return response
except IOError, e:
if hasattr(e, 'code'):
print '%s - ERROR %s' % (self.url, e.code)
return None
else:
return response