[英]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
这是对上述函数的修改,它允许参数init
或term
均为nil
。 如果init
为nil
,则提取文本直到term
定界符。 如果term
为nil
,则从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请求的工作示例可以在此处看到:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.