Python:httplib
lastmod 2026-05-13created 2015-10-299 edits
Simple http server
To quickly start an HTTP server, run the following.
Example
Here is an example session that uses the GET method:
>>> import httplib
>>> conn = httplib.HTTPSConnection("www.python.org")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read()
>>> conn.request("GET", "/")
>>> r2 = conn.getresponse()
>>> print r2.status, r2.reason
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
Here is an example session that uses the HEAD method. Note that the HEAD method never returns any data.
>>> import httplib
>>> conn = httplib.HTTPSConnection("www.python.org")
>>> conn.request("HEAD","/")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
>>> data = res.read()
>>> print len(data)
0
>>> data == ''
Here is an example session that shows how to POST requests:
>>> 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()
Client side HTTP PUT requests are very similar to POST requests. The difference lies only the server side where HTTP server will allow resources to be created via PUT request. Here is an example session that shows how to do PUT request using httplib:
>>> # This creates an HTTP message
>>> # with the content of BODY as the enclosed representation
>>> # for the resource http://localhost:8080/foobar
...
>>> import httplib
>>> BODY = "***filecontents***"
>>> conn = httplib.HTTPConnection("localhost", 8080)
>>> conn.request("PUT", "/file", BODY)
>>> response = conn.getresponse()
>>> print response.status, response.reason
200, OK
Troubleshooting
CERTIFICATE_VERIFY_FAILED
See CERTIFICATE_VERIFY_FAILED for details.
See also
- Python
- Python:urllib
- Python:urllib2
- Python:http
- Python:httplib
- Python:Requests
- aiohttp
- uploadserver
- Goshs - Feature-rich single-binary file server for developers
Favorite site
- httplib - HTTP protocol client
- ssl - TLS/SSL wrapper for socket objects
- Web client programming with Python
Pages that link here