使用 AsyncHTTPClient 时 tornado post xml 数据如何?

How does tornado post xml data when using AsyncHTTPClient?

我使用 Tornado 4.2,我需要使用 POST 请求发送 xml 数据。如果我使用 requests 库,它会按预期工作:

 r = requests.post(url, headers=headers, data=send_xml, verify=False)
 prepay_result_dic = cls.trans_xml_to_dict(r.content)

如何使用 tornado.httpclient.AsyncHTTPClient 实现相同的功能?我试过:

@tornado.gen.coroutine
def post_async_url(url, payload={}, headers={}):
    '''
    post url,to replace the requests lib...
    :param url: "http://www.google.com/"
    :param payload: {'userId': user_id}
    :return: response.body
    '''
    import urllib
    http_client = tornado.httpclient.AsyncHTTPClient()
    payload = urllib.urlencode(payload)
    response = yield tornado.gen.Task(http_client.fetch, url, method="POST", headers=headers, body=payload, validate_cert=False)
    raise tornado.gen.Return(response.body)

但是上面的代码引发了一个错误:

TypeError: not a valid non-string sequence or mapping object

此错误不是来自 Tornado,而是来自 urllib.urlencode,当您尝试在字符串而不是字典上调用该函数时可能会发生。评论表明 payload 应该是一个字典,但由于您的问题是询问 XML,所以 payload 是一个字符串吗?如果是这样,您可以直接将其作为请求的 body 传递,而无需对它进行 url 编码。