diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py index be1da0735b98fd..f2a96052b3fd2d 100644 --- a/Lib/test/test_urllib2.py +++ b/Lib/test/test_urllib2.py @@ -1465,6 +1465,33 @@ def redirect(h, req, url=to_url): urllib.request.HTTPRedirectHandler.max_redirections) err.close() + def test_redirect_does_not_read_body(self): + # The body of a redirect response is closed without being read. + from_url = "http://example.com/a.html" + to_url = "http://example.com/b.html" + + class UnreadFile(MockFile): + read_called = closed = False + + def read(self, count=None): + self.read_called = True + + def close(self): + self.closed = True + + for code in 301, 302, 303, 307, 308: + with self.subTest(code=code): + h = urllib.request.HTTPRedirectHandler() + o = h.parent = MockOpener() + req = Request(from_url) + req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT + fp = UnreadFile() + getattr(h, "http_error_%s" % code)( + req, fp, code, "Blah", MockHeaders({"location": to_url})) + self.assertFalse(fp.read_called) + self.assertTrue(fp.closed) + self.assertEqual(o.req.get_full_url(), to_url) + def test_invalid_redirect(self): from_url = "http://example.com/a.html" valid_schemes = ['http','https','ftp'] diff --git a/Lib/urllib/request.py b/Lib/urllib/request.py index 26c27fd5b2c3ab..63bbdb3dc5843f 100644 --- a/Lib/urllib/request.py +++ b/Lib/urllib/request.py @@ -717,7 +717,6 @@ def http_error_302(self, req, fp, code, msg, headers): # Don't close the fp until we are sure that we won't use it # with HTTPError. - fp.read() fp.close() return self.parent.open(new, timeout=req.timeout) diff --git a/Misc/NEWS.d/next/Library/2026-12-03-21-53-41.gh-issue-163110.jZ9Kdo.rst b/Misc/NEWS.d/next/Library/2026-12-03-21-53-41.gh-issue-163110.jZ9Kdo.rst new file mode 100644 index 00000000000000..6267f976ae8ab0 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-12-03-21-53-41.gh-issue-163110.jZ9Kdo.rst @@ -0,0 +1,2 @@ +:class:`urllib.request.HTTPRedirectHandler` no longer reads the body of a +redirect response before following the redirect.