使用带有龙卷风的 HTTP POST 发送 JSON 不起作用

sending a JSON using HTTP POST with tornado dont work

我使用 python3 和龙卷风发送 JSON 使用 HTTP POST 请求,就像这样。

Server.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 = {}

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

Console

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,而不是那样。

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