Skip to content
Open
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
17 changes: 17 additions & 0 deletions Lib/test/test_urllib2.py
Original file line number Diff line number Diff line change
Expand Up @@ -980,6 +980,23 @@ def test_http(self):
self.assertEqual(req.unredirected_hdrs["Host"], "baz")
self.assertEqual(req.unredirected_hdrs["Spam"], "foo")

def test_http_header_priority(self):
# gh-47005: regular headers set via add_header() must override
# unredirected headers with the same name in do_open(), consistent
# with get_header() and header_items().
h = urllib.request.AbstractHTTPHandler()
h.parent = MockOpener()

req = Request("http://example.com/", headers={"Content-Type": "application/json"})
req.timeout = None
req.add_unredirected_header("Content-Type", "application/x-www-form-urlencoded")

http = MockHTTPClass()
h.do_open(http, req)

sent_headers = dict(http.req_headers)
self.assertEqual(sent_headers["Content-Type"], "application/json")

def test_http_body_file(self):
# A regular file - chunked encoding is used unless Content Length is
# already set.
Expand Down
3 changes: 1 addition & 2 deletions Lib/urllib/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -1293,8 +1293,7 @@ def do_open(self, http_class, req, **http_conn_args):
h.set_debuglevel(self._debuglevel)

headers = dict(req.unredirected_hdrs)
headers.update({k: v for k, v in req.headers.items()
if k not in headers})
headers.update(req.headers)

# TODO(jhylton): Should this be redesigned to handle
# persistent connections?
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix :meth:`!urllib.request.AbstractHTTPHandler.do_open` to give regular
headers set via :meth:`~urllib.request.Request.add_header` priority over
unredirected headers, consistent with :meth:`~urllib.request.Request.get_header`
and :meth:`~urllib.request.Request.header_items`.
Loading