diff --git a/src/ahttpx/_request.py b/src/ahttpx/_request.py index 6731259..78b8228 100644 --- a/src/ahttpx/_request.py +++ b/src/ahttpx/_request.py @@ -53,6 +53,17 @@ def __init__( elif content_length > 0: self.headers = self.headers.copy_set("Content-Length", str(content_length)) + elif method in ("POST", "PUT", "PATCH"): + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2 + # RFC 7230, Section 3.3.2, Content Length. + # + # A user agent SHOULD send a Content-Length in a request message when no + # Transfer-Encoding is sent and the request method defines a meaning for + # an enclosed payload body. For example, a Content-Length header field is + # normally sent in a POST request even when the value is 0. + # (indicating an empty payload body). + self.headers = self.headers.copy_set("Content-Length", "0") + @property def body(self) -> bytes: if not hasattr(self, '_body'): diff --git a/src/httpx/_request.py b/src/httpx/_request.py index 0d5c8a6..1b739b1 100644 --- a/src/httpx/_request.py +++ b/src/httpx/_request.py @@ -53,6 +53,17 @@ def __init__( elif content_length > 0: self.headers = self.headers.copy_set("Content-Length", str(content_length)) + elif method in ("POST", "PUT", "PATCH"): + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2 + # RFC 7230, Section 3.3.2, Content Length. + # + # A user agent SHOULD send a Content-Length in a request message when no + # Transfer-Encoding is sent and the request method defines a meaning for + # an enclosed payload body. For example, a Content-Length header field is + # normally sent in a POST request even when the value is 0. + # (indicating an empty payload body). + self.headers = self.headers.copy_set("Content-Length", "0") + @property def body(self) -> bytes: if not hasattr(self, '_body'): diff --git a/tests/test_request.py b/tests/test_request.py index c7a8db7..a69e1d1 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -64,3 +64,16 @@ def test_request_json(): "Content-Type": "application/json", } assert r.read() == b'{"msg":"Hello, world"}' + + +def test_request_empty_post(): + r = httpx.Request("POST", "https://example.com") + + assert repr(r) == "" + assert r.method == "POST" + assert r.url == "https://example.com" + assert r.headers == { + "Host": "example.com", + "Content-Length": "0", + } + assert r.read() == b''