Tornado PUT 请求缺少主体
我正在尝试使用tornado的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)
但是,当请求到达我想要的地址时,似乎没有发送请求体,尽管我在上面已经正确地编码和定义了这个请求体。请问我是不是漏掉了什么?
3 个回答
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)
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×tamp=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
5
如果另一端在期待接收JSON格式的数据,你可能需要设置一个“内容类型”头信息。可以试试这样做:
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的字符串。