当contenttype为“application/xml”时,如何使用httplib发布非科学字符

2024-05-16 05:20:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python2.7中实现了一个关键的跟踪程序API模块。Pivotal Tracker API要求POST数据是XML文档,“application/XML”是内容类型。在

我的代码使用urlib/httplib发布文档,如下所示:

    request = urllib2.Request(self.url, xml_request.toxml('utf-8') if xml_request else None, self.headers)
    obj = parse_xml(self.opener.open(request))

当XML文本包含非ASCII字符时,将产生异常:

^{pr2}$

正如我所看到的,httplib.\u send_output正在为消息有效载荷创建一个ASCII字符串,大概是因为它希望数据是URL编码的(application/x-www-form-urlencoded)。只要只使用ASCII字符,它就可以很好地处理application/xml。在

有没有一种简单的方法来发布包含非ASCII字符的application/xml数据,或者我必须跳转(例如,使用Twistd和自定义的post有效负载生成器)?在


Tags: 模块数据文档self程序apiapplicationrequest
3条回答

与JF Sebastian answer相同,但我添加了一个新的,这样代码格式就可以工作了(而且更适合google)

如果您试图标记到mechanize表单请求的末尾,会发生以下情况:

br = mechanize.Browser()
br.select_form(nr=0)
br['form_thingy'] = u"Wonderful"
headers = dict((k.encode('ascii') if isinstance(k, unicode) else k, v.encode('ascii') if isinstance(v, unicode) else v) for k,v in br.request.headers.items())
br.addheaders = headers
req = br.submit()

检查self.url是否为unicode。如果是unicode,则httplib将把数据视为unicode。在

你可以强制编码自我.url对于unicode,则httplib将所有数据视为unicode

你混合了Unicode和bytestrings。在

>>> msg = u'abc' # Unicode string
>>> message_body = b'\xc5' # bytestring
>>> msg += message_body
Traceback (most recent call last):
  File "<input>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal \
not in range(128)

要修复它,请确保self.headers内容已正确编码,即headers中的所有键、值都应该是bytestrings:

^{pr2}$

注意:头的字符编码与正文的字符编码无关,也就是说,xml文本可以独立编码(从http消息的角度来看,它只是一个八位字节流)。在

对于self.url-如果它具有unicode类型,则将其转换为bytestring(使用'ascii'字符编码)。在


HTTP message consists of a start-line, "headers", an empty line and possibly a message-body所以self.headers用于头,self.url用于起始行(http方法在这里),并且可能用于Hosthttp报头(如果客户端是http/1.1),XML文本将转到消息体(作为二进制blob)。在

self.url使用ASCII编码总是安全的(IDNA可以用于非ASCII域名,结果也是ASCII)。在

以下是rfc 7230 says about http headers character encoding

Historically, HTTP has allowed field content with text in the ISO-8859-1 charset [ISO-8859-1], supporting other charsets only through use of [RFC2047] encoding. In practice, most HTTP header field values use only a subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD limit their field values to US-ASCII octets. A recipient SHOULD treat other octets in field content (obs-text) as opaque data.

要将XML转换为bytestring,请参见^{} encoding condsiderations

The use of UTF-8, without a BOM, is RECOMMENDED for all XML MIME entities.

相关问题 更多 >