Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "Content-Length: 0" on POST, PUT, PATCH if required. #995

Merged
merged 2 commits into from
May 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions httpx/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,9 @@ def prepare(self) -> None:
auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []

has_host = "host" in self.headers
has_content_length = (
"content-length" in self.headers or "transfer-encoding" in self.headers
)
has_user_agent = "user-agent" in self.headers
has_accept = "accept" in self.headers
has_accept_encoding = "accept-encoding" in self.headers
Expand All @@ -626,6 +629,8 @@ def prepare(self) -> None:
if url.userinfo:
url = url.copy_with(username=None, password=None)
auto_headers.append((b"host", url.authority.encode("ascii")))
if not has_content_length and self.method in ("POST", "PUT", "PATCH"):
auto_headers.append((b"content-length", b"0"))
if not has_user_agent:
auto_headers.append((b"user-agent", USER_AGENT.encode("ascii")))
if not has_accept:
Expand Down
16 changes: 16 additions & 0 deletions tests/client/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,22 @@ def test_build_request(server):
assert response.json()["Custom-header"] == "value"


def test_build_post_request(server):
url = server.url.copy_with(path="/echo_headers")
headers = {"Custom-header": "value"}

with httpx.Client() as client:
request = client.build_request("POST", url)
request.headers.update(headers)
response = client.send(request)

assert response.status_code == 200
assert response.url == url

assert response.json()["Content-length"] == "0"
assert response.json()["Custom-header"] == "value"


def test_post(server):
with httpx.Client() as client:
response = client.post(server.url, data=b"Hello, world!")
Expand Down