5

I need to send a post request to a web server with only 'Host' & 'Content-Length' headers. I have specified these two headers in the dictionary which I pass to requests module, but it adds 'Accept', 'Accept-Encoding', 'User-Agent' headers.

Python code:

headers = {'Content-Length': content_length, 'Host': 'Server-1:8080'}
r = requests.post(url, data=data, headers=headers)
print(r.request.headers)

Actual request headers sent:

{'Accept': '*/*', 'Host': 'Server-1:8080', 'Content-Length': '3072', 'User-Agent': 'python-requests/2.6.0 CPython/3.4.1 Windows/7', 'Connection': 'keep-alive, 'Accept-Encoding': 'gzip, deflate'}

How can I limit the headers sent by requests module?

1 Answer 1

6

From a read of the docs it looks like those are session level parameters which you can force to be omitted by setting their values to None.

headers = {'Content-Length': content_length, 'Host': 'Server-1:8080',
           'User-Agent': None, 'Connection': None, 'Accept-Encoding': None}
Sign up to request clarification or add additional context in comments.

1 Comment

These days, setting Host, User-Agent or Accept-Encoding to None doesn't work. It causes Requests to send them with their default values instead of not sending them at all. For those 3 you have to do import urllib3 then headers = {'Host': urllib3.util.SKIP_HEADER, 'User-Agent': urllib3.util.SKIP_HEADER, 'Accept-Encoding': urllib3.util.SKIP_HEADER}. See #5671 for details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.