如何从 HTTP 请求中获取发送到 NodeMCU 上的 Lua 帖子参数

我通过 Tasker(安卓应用程序)向我的 NodeMCU 发送了此 HTTP POST 请求,如下所示:

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>

我只想提取在“”和“”参数之间的内容。我该如何做到这一点?

点赞
用户6879826
用户6879826

该函数允许你从两个字符串分隔符之间提取文本:

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

这是上面函数的修改版,允许 initterm 参数中的任何一个为 nil。如果 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>
2017-02-04 20:12:50
用户8171569
用户8171569

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

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

可以在这里看到使用你提问中给出的 HTTP 请求的可行示例:

https://repl.it/repls/GlamorousAnnualConferences

2018-08-03 12:15:34