diff --git a/Lib/test/test_urllib2net.py b/Lib/test/test_urllib2net.py index 56e952d1478..5ace162e7b6 100644 --- a/Lib/test/test_urllib2net.py +++ b/Lib/test/test_urllib2net.py @@ -172,6 +172,18 @@ class OtherNetworkTests(unittest.TestCase): finally: res.close() + def test_custom_headers(self): + url = "http://www.example.com" + opener = urllib2.build_opener() + request = urllib2.Request(url) + self.assertFalse(request.header_items()) + opener.open(request) + self.assertTrue(request.header_items()) + self.assertTrue(request.has_header('User-agent')) + request.add_header('User-Agent','Test-Agent') + opener.open(request) + self.assertEqual(request.get_header('User-agent'),'Test-Agent') + def _test_urls(self, urls, handlers, retry=True): import time import logging diff --git a/Lib/urllib2.py b/Lib/urllib2.py index 5c717a4c5d9..adc6d8c55a9 100644 --- a/Lib/urllib2.py +++ b/Lib/urllib2.py @@ -1127,8 +1127,10 @@ class AbstractHTTPHandler(BaseHandler): h = http_class(host, timeout=req.timeout) # will parse host:port h.set_debuglevel(self._debuglevel) - headers = dict(req.headers) - headers.update(req.unredirected_hdrs) + headers = dict(req.unredirected_hdrs) + headers.update(dict((k, v) for k, v in req.headers.items() + if k not in headers)) + # We want to make an HTTP/1.1 request, but the addinfourl # class isn't prepared to deal with a persistent connection. # It will try to read all remaining data from the socket,