diff --git a/aiohttp/client_reqrep.py b/aiohttp/client_reqrep.py index 3dacbecf3dc..5100c394ce7 100644 --- a/aiohttp/client_reqrep.py +++ b/aiohttp/client_reqrep.py @@ -89,7 +89,7 @@ def __init__(self, method, url, *, self.update_headers(headers) self.update_auto_headers(skip_auto_headers) self.update_cookies(cookies) - self.update_content_encoding() + self.update_content_encoding(data) self.update_auth(auth) self.update_body_from_data(data, skip_auto_headers) @@ -230,8 +230,11 @@ def update_cookies(self, cookies): self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip() - def update_content_encoding(self): + def update_content_encoding(self, data): """Set request content encoding.""" + if not data: + return + enc = self.headers.get(hdrs.CONTENT_ENCODING, '').lower() if enc: if self.compress is not False: diff --git a/tests/test_client_request.py b/tests/test_client_request.py index a4f41a66f55..c0782537d26 100644 --- a/tests/test_client_request.py +++ b/tests/test_client_request.py @@ -528,7 +528,7 @@ def test_bytes_data(self): @unittest.mock.patch('aiohttp.client_reqrep.aiohttp') def test_content_encoding(self, m_http): - req = ClientRequest('get', 'http://python.org/', + req = ClientRequest('get', 'http://python.org/', data='foo', compress='deflate', loop=self.loop) resp = req.send(self.transport, self.protocol) self.assertEqual(req.headers['TRANSFER-ENCODING'], 'chunked') @@ -538,10 +538,20 @@ def test_content_encoding(self, m_http): self.loop.run_until_complete(req.close()) resp.close() + @unittest.mock.patch('aiohttp.client_reqrep.aiohttp') + def test_content_encoding_dont_set_headers_if_no_body(self, m_http): + req = ClientRequest('get', 'http://python.org/', + compress='deflate', loop=self.loop) + resp = req.send(self.transport, self.protocol) + self.assertNotIn('TRANSFER-ENCODING', req.headers) + self.assertNotIn('CONTENT-ENCODING', req.headers) + self.loop.run_until_complete(req.close()) + resp.close() + @unittest.mock.patch('aiohttp.client_reqrep.aiohttp') def test_content_encoding_header(self, m_http): req = ClientRequest( - 'get', 'http://python.org/', + 'get', 'http://python.org/', data='foo', headers={'Content-Encoding': 'deflate'}, loop=self.loop) resp = req.send(self.transport, self.protocol) self.assertEqual(req.headers['TRANSFER-ENCODING'], 'chunked')