如何从 lua 发送到 NodeMCU 的 http 请求中获取 post 参数

How to get post parameters from http request in lua sent to NodeMCU

我通过 Tasker(Android 应用程序)将此 HTTP POST 请求发送到我的 NodeMCU,如下所示:

POST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
User-Agent: Tasker/4.9u4m (Android/6.0.1)
Connection: close
Content-Length: 10
Host: 192.168.0.22
Accept-Encoding: gzip

<action>Play</action><SetVolume>5</SetVolume>

我只想提取“”和“”参数之间的内容。我该怎么做?

此函数允许您从两个字符串定界符之间提取文本:

function get_text (str, init, term)
   local _, start = string.find(str, init)
   local stop = string.find(str, term)
   local result = nil
   if _ and stop then
      result = string.sub(str, start + 1, stop - 1)
   end
   return result
end

交互示例:

> msg = "<action>Play</action><SetVolume>5</SetVolume>"
> get_text(msg, "<action>", "<SetVolume>")
Play</action>
> get_text(msg, "<action>", "</SetVolume>")
Play</action><SetVolume>5

这是对上述函数的修改,允许 nil 用于参数 initterm。如果 initnil,那么文本将被提取到 term 定界符。如果 termnil,则从 init 之后提取文本到字符串末尾。

function get_text (str, init, term)
   local _, start
   local stop = (term and string.find(str, term)) or 0
   local result = nil
   if init then
      _, start = string.find(str, init)
   else
      _, start = 1, 0
   end

   if _ and stop then
      result = string.sub(str, start + 1, stop - 1)
   end
   return result
end

交互示例:

> msg = "<action>Play</action><SetVolume>5</SetVolume>"
> get_text(msg)
<action>Play</action><SetVolume>5</SetVolume>
> get_text(msg, nil, '<SetVolume>')
<action>Play</action>
> get_text(msg, '</action>')
<SetVolume>5</SetVolume>
> get_text(msg, '<action>', '<SetVolume>')
Play</action>

为了完整起见,这是我想出的另一个解决方案:

string.gsub(request, "<(%a+)>([^<]+)</%a+>", function(key, val)
  print(key .. ": " .. val)
end)

可以在此处查看在您的问题中使用给定 HTTP 请求的工作示例:

https://repl.it/repls/GlamorousAnnualConferences