Python – How do I set any host header in Python 3 urllib?

How do I set any host header in Python 3 urllib?… here is a solution to the problem.

How do I set any host header in Python 3 urllib?

For example, I want to send a request to 12.34.56.78 with a host header of stackoverflow.com. However, Python seems to override the Host header, and the actual package sent is Host: 12.34.56.78.

How can I stop this behavior?

from urllib import request
a = request.build_opener()
a.addheaders.append(('Host', 'stackoverflow.com'))
a.open('http://12.34.56.78/')

Note: The code runs on Python 3

Solution

Thank you Blurp for his thoughts, one way to send a request is:

from urllib import request
r = request. Request('http://12.34.56.78/', headers={'Host': 'stackoverflow.com'})
request.urlopen(r)

Related Problems and Solutions