Eric Stdlib
Eric Stdlib

Reputation: 1562

How can I set an arbitary Host header in Python 3 urllib?

For example, I would like to send a request to 12.34.56.78 with host header stackoverflow.com. However, Python seems to overwrite the Host header, and the actual packet sent still has 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

Upvotes: 3

Views: 6437

Answers (1)

Eric Stdlib
Eric Stdlib

Reputation: 1562

Thanks Blurp for his idea, a way to send the request is:

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

Upvotes: 4

Related Questions