all Python 3urllib.requestterm
urllib.request.HTTPHandler
protocol handlers
The handler for http:// URLs: it fills in service headers before sending and opens the connection through http.client.
Syntax
urllib.request.HTTPHandler(debuglevel=0)
For a request with data it sets Content-Type: application/x-www-form-urlencoded and Content-Length itself, so send JSON with an explicit Content-Type: application/json header, or the server reads the body as a form. It rejects a str body with TypeError. HTTPHandler(debuglevel=1) prints the whole exchange with the server, which helps debugging.
Examples
import urllib.request
handler = urllib.request.HTTPHandler()
urllib.request.OpenerDirector().add_handler(handler)
req = urllib.request.Request('http://example.com/api', data=b'{"a": 1}')
handler.http_request(req) # готовит запрос, в сеть не ходит
print(req.get_header('Content-type'), req.get_header('Content-length'))
# → application/x-www-form-urlencoded 8
import urllib.request
req = urllib.request.Request('http://example.com/api', data='a=1')
try:
urllib.request.HTTPHandler().http_request(req)
except TypeError as e:
print(str(e)[:33]) # → POST data should be bytes, an ite
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy