Search code examples
python-3.xtornado

sending a JSON using HTTP POST with tornado dont work


im using python3 and tornado to send a JSON using a HTTP POST request, like this.

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

I dont know why it not work, i try the same request on postman and it works perfect and trying the code i get this response:

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={})

It seems to be working right, but the response should be a json, not that.


Solution

  • It looks to me like everything worked. HTTPResponse is an object with attributes like headers and body, but its string form is not very friendly. You probably want to print(response.body) instead of the response object itself. Then you'll see the server response, which you can parse with json.loads(response.body).