【问题标题】:sending a JSON using HTTP POST with tornado dont work使用带有龙卷风的 HTTP POST 发送 JSON 不起作用
【发布时间】:2018-11-09 23:01:57
【问题描述】:

我使用 python3 和 tornado 使用 HTTP POST 请求发送 JSON,如下所示。

服务器.py

@gen.coroutine
def getResponseWS(self, url, contentBody, method='POST'):
    import tornado.ioloop
    import tornado.web
    import tornado.options
    from tornado import gen
    from tornado.httpclient import HTTPClient
    from tornado.escape import json_decode, json_encode
    import json

    http_client = tornado.httpclient.AsyncHTTPClient()
    headers = {
               'Content-Type': 'application/json; charset=UTF-8'
           }
    simplejson = json.dumps(contentBody)
    #-------------------------------------------
    # contentBody = {"some_key": "some_value"}
    # url = 'http://some_ip_address:8088/testService'
    #
    baseLogger.info("Data to be send to webservice:%s" % simplejson)
    try:
        request = tornado.httpclient.HTTPRequest(url=url, method=method, headers=headers, body=simplejson)
        response = yield http_client.fetch(request)
        print("-------SERVICE RESPONSE-----------")
        print(response)
    except Exception as e:
        baseLogger.info("SERVICE RESPONSE:%s" % e)
        contentJson = {}

我不知道为什么它不起作用,我在邮递员上尝试了相同的请求,它完美地工作并尝试了我得到这个响应的代码:

控制台

11-08 16:14:01 BaseLogger  :INFO   IP:[127.0.0.1] -Data to be send to webservice:{"some_key": "some_value"}

-------SERVICE RESPONSE-----------
HTTPResponse(_body=None,buffer=<_io.BytesIO object at 0x7fda25fad048>,code=200,effective_url='http://some_ip_address:8088/testService',error=None,headers=<tornado.httputil.HTTPHeaders object at 0x7fda45a9d160>,reason='OK',request=<tornado.httpclient.HTTPRequest object at 0x7fda25f7db38>,request_time=0.8046760559082031,time_info={})

它似乎工作正常,但响应应该是一个 json,而不是那个。

【问题讨论】:

    标签: python-3.x tornado


    【解决方案1】:

    在我看来一切正常。 HTTPResponse 是一个具有headersbody 等属性的对象,但它的字符串形式不是很友好。您可能想要print(response.body) 而不是响应对象本身。然后您将看到服务器响应,您可以使用json.loads(response.body) 对其进行解析。

    【讨论】:

    • 这很奇怪,因为打印整个响应不显示任何正文,但打印 response.body 显示我想要的正确数据
    猜你喜欢
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多