Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5fa4a89

Browse files
committed
Fix Issue14721: Send Content-length: 0 for empty body () in the http.client requests
1 parent 1be320e commit 5fa4a89

3 files changed

Lines changed: 32 additions & 1 deletion

File tree

Lib/http/client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -997,7 +997,7 @@ def _send_request(self, method, url, body, headers):
997997

998998
self.putrequest(method, url, **skips)
999999

1000-
if body and ('content-length' not in header_names):
1000+
if body is not None and ('content-length' not in header_names):
10011001
self._set_content_length(body)
10021002
for hdr, value in headers.items():
10031003
self.putheader(hdr, value)

Lib/test/test_httplib.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,34 @@ def append(self, item):
9999
conn.request('POST', '/', body, headers)
100100
self.assertEqual(conn._buffer.count[header.lower()], 1)
101101

102+
def test_content_length_0(self):
103+
104+
class ContentLengthChecker(list):
105+
def __init__(self):
106+
list.__init__(self)
107+
self.content_length = None
108+
def append(self, item):
109+
kv = item.split(b':', 1)
110+
if len(kv) > 1 and kv[0].lower() == b'content-length':
111+
self.content_length = kv[1].strip()
112+
list.append(self, item)
113+
114+
# POST with empty body
115+
conn = client.HTTPConnection('example.com')
116+
conn.sock = FakeSocket(None)
117+
conn._buffer = ContentLengthChecker()
118+
conn.request('POST', '/', '')
119+
self.assertEqual(conn._buffer.content_length, b'0',
120+
'Header Content-Length not set')
121+
122+
# PUT request with empty body
123+
conn = client.HTTPConnection('example.com')
124+
conn.sock = FakeSocket(None)
125+
conn._buffer = ContentLengthChecker()
126+
conn.request('PUT', '/', '')
127+
self.assertEqual(conn._buffer.content_length, b'0',
128+
'Header Content-Length not set')
129+
102130
def test_putheader(self):
103131
conn = client.HTTPConnection('example.com')
104132
conn.sock = FakeSocket(None)

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ Core and Builtins
6363
Library
6464
-------
6565

66+
- Issue #14721: Send the correct 'Content-length: 0' header when the body is an
67+
empty string ''. Initial Patch contributed by Arve Knudsen.
68+
6669
- Issue #9374: Generic parsing of query and fragment portions of url for any
6770
scheme. Supported both by RFC3986 and RFC2396.
6871

0 commit comments

Comments
 (0)