6

我正在尝试使用龙卷风 ASyncHTTPClient 发出 put 请求,如下所示:

  data = { 'text': 'important text',
           'timestamp': 'an iso timestamp' }

  request = tornado.httpclient.HTTPRequest(URL, method = 'PUT', body = urllib.urlencode(data))

  response = yield Task(tornado.httpclient.ASyncHTTPClient().fetch, request)

但是,当请求到达其所需的端点时,它似乎没有正文,尽管上述正文已在上面正确编码和定义。有什么我在这里忽略的吗?


4

3 回答 3

5

如果另一端需要 JSON,您可能需要设置“Content-Type”标头。试试这个:

data = { 'text': 'important text',
       'timestamp': 'an iso timestamp' }

headers = {'Content-Type': 'application/json; charset=UTF-8'}

request = tornado.httpclient.HTTPRequest(URL, method = 'PUT', headers = headers, body = simplejson.dumps(data))

response = yield Task(tornado.httpclient.ASyncHTTPClient().fetch, request)

这样,标头告诉服务器您正在发送 JSON,而正文是可以解析为 JSON 的字符串。

于 2013-03-25T22:14:54.897 回答
2

问题可能在另一端。
以下使用 Tornado 2.4.1 的测试产生了预期的输出。

import logging
import urllib

from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler, asynchronous
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from tornado import gen, options

log = logging.getLogger()
options.parse_command_line()

class PutBodyTest(RequestHandler):
    @asynchronous
    @gen.engine
    def get(self):
        data = {
            'text': 'important text',
            'timestamp': 'a timestamp'
        }
        req = HTTPRequest(
            'http://localhost:8888/put_body_test',
            method='PUT',
            body=urllib.urlencode(data)
        )
        res = yield gen.Task(AsyncHTTPClient().fetch, req)
        self.finish()

    def put(self):
        log.debug(self.request.body)

application = Application([
    (r"/put_body_test", PutBodyTest),
])

if __name__ == "__main__":
    application.listen(8888)
    IOLoop.instance().start()

日志输出:

$ python put_test.py --logging=debug
[D 130322 11:45:24 put_test:30] text=important+text&timestamp=a+timestamp
[I 130322 11:45:24 web:1462] 200 PUT /put_body_test (127.0.0.1) 0.37ms
[I 130322 11:45:24 web:1462] 200 GET /put_body_test (::1) 9.76ms
于 2013-03-22T18:53:13.063 回答
0

这是期望 JSON 的发布请求!试试这个:

    @gen.coroutine
    def post(self):
        http_client = AsyncHTTPClient()
        http_client = tornado.httpclient.AsyncHTTPClient()

        URL = "http://localhost:1338/api/getPositionScanByDateRange"
        data = {"startDate":"2017-10-31 18:30:00","endDate":"2018-02-08 12:09:14","groupId":3} #A dictionary of your post data
        headers = {'Content-Type': 'application/json; charset=UTF-8'}

        record = yield http_client.fetch(URL, method = 'POST', headers = headers, body = json.dumps(data))

        if record.error:
            response = record.error
        else:
            response = record.body
        self.set_header('Content-Type', 'application/json')
        self.finish(response)
于 2018-02-09T10:47:09.630 回答