【问题标题】:How to get post parameters from http request in lua sent to NodeMCU如何从发送到NodeMCU的lua中的http请求中获取post参数
【发布时间】:2017-06-21 23:35:45
【问题描述】:

我通过 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>

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

【问题讨论】:

  • My first solution 对您的其他问题可能会有所帮助。您期望的具体输出是什么?
  • 是的,你的回答解决了我的问题,我想也许改写我的问题会更简单

标签: http post lua nodemcu


【解决方案1】:

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

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

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

https://repl.it/repls/GlamorousAnnualConferences

【讨论】:

    【解决方案2】:

    此功能允许您从两个字符串分隔符之间提取文本:

    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>
    

    【讨论】:

      猜你喜欢
      • 2013-01-11
      • 2017-08-23
      • 2016-06-02
      • 2018-02-18
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多