Python: BaseHTTPRequestHandler - Read raw post

可紊 提交于 2020-01-03 07:09:12

问题


How do I read the raw http post STRING. I've found several solutions for reading a parsed version of the post, however the project I'm working on submits a raw xml payload without a header. So I am trying to find a way to read the post data without it being parsed into a key => value array.


回答1:


I think self.rfile.read(self.headers.getheader('content-length')) should return the raw data as a string. According to the docs directly inside the BaseHTTPRequestHandler class:

- rfile is a file object open for reading positioned at the
start of the optional input data part;



回答2:


self.rfile.read(int(self.headers.getheader('Content-Length'))) will return the raw HTTP POST data as a string.

Breaking it down:

  1. The header 'Content-Length' specifies how many bytes the HTTP POST data contains.
  2. self.headers.getheader('Content-Length') returns the content length (value of the header) as a string.
  3. This has to be converted to an integer before passing as parameter to self.rfile.read(), so use the int() function.

Also, note that the header name is case sensitive so it has to be specified as 'Content-Length' only.

Edit: Apparently header field is not case sensitive (at least in Python 2.7.5) which I believe is the correct behaviour since https://tools.ietf.org/html/rfc2616 states:

Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive.




回答3:


For python 3.7 the below worked for me:

rawData = (self.rfile.read(int(self.headers['content-length']))).decode('utf-8')

With the help of the other answers in this question and this and this. The last link actually contains the full solution.



来源:https://stackoverflow.com/questions/17888504/python-basehttprequesthandler-read-raw-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!