0

所以我的问题在于尝试使用 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
4

1 回答 1

2

我修好了。对于以后在 google 上搜索的任何人,问题在于在我将数据编码为 utf-8 之前明确设置 Content-Length 标头。删除 content-length 标头(由 urllib2 自动设置)修复了该问题。

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

于 2013-10-30T19:57:34.083 回答