Search code examples
pythonpython-requests

How can I change Content-Length in Python?


I want to change Content-Length of my request, as I see by default it's "168". Also I would know what used Content-Length for. Some sites give me net::ERR_CONTENT_LENGTH_MISMATCH (e.g. api sites) so I hope I can fix that and also I would know what is that error (mentioned upper). And do I need to change it or there another way of fixing it?

I tried this but it didn't worked at all:

import requests
session = requests.Session()
session.headers.update({ "Content-length": "2" })
session.post("https://example.com/")

Solution

  • what used Content-Length for.

    From RFC 1945

    When an Entity-Body is included with a message, the length of that body may be determined in one of two ways. If a Content-Length header field is present, its value in bytes represents the length of the Entity-Body. Otherwise, the body length is determined by the closing of the connection by the server.

    Closing the connection cannot be used to indicate the end of a request body, since it leaves no possibility for the server to send back a response. Therefore, HTTP/1.0 requests containing an entity body must include a valid Content-Length header field. If a request contains an entity body and Content-Length is not specified, and the server does not recognize or cannot calculate the length from other fields, then the server should send a 400 (bad request) response.

    therefore value in Content-Length should describe size (in bytes) of body of given request.

    session.headers.update({ "Content-length": "2" })
    session.post("https://example.com/")
    

    This piece of code is mutually exclusive, you at same time inform server to expect 2 bytes body and then send bodyless requests. If you wish to send bodyless request and Content-Length, value of it should be zero ({"Content-length":"0"})