Python Urllib2发布Utf-8数据会产生400错误

时间:2013-10-30 19:41:50

标签: python xml soap urllib2

所以我的问题在于尝试使用urrlib2为SOAP请求发布一些数据。

数据是唯一包含任何非ascii字符的内容。

API_ENDPOINT = "https://www.foo.com/WebService/v1_2/fooService.asmx"
headers = {
        'Host': 'www.foo.com',
        'Content-Type': 'text/xml; charset=utf-8',
        'Content-length': "%d" % len(data_xml),
        'SOAPAction': '"https://www.foo.com/SaveJob"',
}
data = some xml unicode stuff
request = urllib2.Request(url=API_ENDPOINT, data=data_xml.encode("utf-8"), headers=headers)

给我这个错误:

content = urllib2.urlopen(request).read()
File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
  return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 400, in open
  response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 513, in http_response
  'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 438, in error
  return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 372, in _call_chain
  result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 521, in http_error_default
  raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 400: Bad Request

1 个答案:

答案 0 :(得分:2)

我修好了。对于稍后在谷歌搜索的任何人,问题是在我将数据编码为utf-8之前明确设置Content-Length标头。删除内容长度标题(由urllib2自动设置)修复了问题。

如果您希望明确设置内容长度,则需要在将数据编码为utf-8后完成。