繁体   English   中英

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

[英]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>

我只想提取“ <action>”和“ <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

这是对上述函数的修改,它允许参数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>

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

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

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

https://repl.it/repls/GlamorousAnnualConferences

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM