Python requests remove Content-Length header from POST

I am using the python requests module to do some tests with the site.

The request module allows you to remove certain headers by going into a dictionary with keys set to None. for example

headers = {u'User-Agent': None}

      

ensures that no user agent is sent with the request.

However, it seems that when I submit the data, requests will calculate the correct Content-Length for me, even if I specify None or the wrong value. For example.

headers = {u'Content-Length': u'999'}
headers = {u'Content-Length': None}

      

I check the response for the headers used in the request (response.request.headers) and I see that the Content-Length has been added with the correct value. So far I do not see an option to disable this behavior

CaseInsensitiveDict({'Content-Length': '39', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept': '*/*', 'User-Agent': 'python-requests/2.2.1 CPython/2.7.6 Linux/3.13.0-36-generic'})

      

I would REALLY like to stay with the requests module for this. Is it possible?

+3


source to share


1 answer


You need to prepare the request manually and then remove the generated content length header:

from requests import Request, Session

s = Session()
req = Request('POST', url, data=data)
prepped = req.prepare()
del prepped.headers['content-length']
response = s.send(prepped)

      



Please note that most compatible HTTP servers can ignore your message body!

If you wanted to use chunked transfer encoding (where you don't need to send the length of the content), use an iterator for data

. See Requested Coded Requests in the documentation. In this case, no title will be set Content-Length

.

+8


source







All Articles