[New-bugs-announce] [issue5550] urllib2 use of opener.addheaders
cocobear
report at bugs.python.org
Tue Mar 24 05:49:02 CET 2009
New submission from cocobear <cocobear.cn at gmail.com>:
take a look at following code:
<code>
import urllib2
headers = [("Content-Type","application/oct-stream"),]
opener = urllib2.build_opener()
opener.addheaders = headers
urllib2.install_opener(opener)
print "after install_opener"
ret = opener.open('http://www.google.com',data="word=ss")
print ret.read()
</code>
I got real send data by wireshark:
POST / HTTP/1.1
Accept-Encoding: identity
Content-Length: 7
Host: www.dict.cn
Content-Type: application/x-www-form-urlencoded
Connection: close
word=ss
I had already set HTTP header of Content-Type, but actally urllib2
change this header.
I got this piece of code from urllib2.py:
if request.has_data(): # POST
data = request.get_data()
if not request.has_header('Content-type'):
request.add_unredirected_header(
'Content-type',
'application/x-www-form-urlencoded')
if not request.has_header('Content-length'):
request.add_unredirected_header(
'Content-length', '%d' % len(data))
scheme, sel = splittype(request.get_selector())
sel_host, sel_path = splithost(sel)
if not request.has_header('Host'):
request.add_unredirected_header('Host', sel_host or host)
for name, value in self.parent.addheaders:
name = name.capitalize()
if not request.has_header(name):
request.add_unredirected_header(name, value)
first,urllib2 will add Content-Type if it's POST method, then it try to
add headers which holded by opener, but there's already 'Content-Type',
so the attribute->addheaders of opener will not append.
I can use Request to add 'Content-Type' header:
request = urllib2.Request(url,headers=headers,data=body)
The example code that I wrote doesn't correct? or it's a problem of urllib2?
----------
components: Library (Lib)
messages: 84058
nosy: cocobear
severity: normal
status: open
title: urllib2 use of opener.addheaders
type: behavior
versions: Python 2.5
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue5550>
_______________________________________
More information about the New-bugs-announce
mailing list