![](/img/trans.png)
[英]How to get post parameters from http request in lua sent to NodeMCU
[英]How to parse chunked HTTP content with Lua on nodemcu?
我有脚本可以在nodemcu和我的服务器之间通信。 它在我的本地主机上运行良好,并在我发送GET请求时解析从服务器检索到的响应。 问题是,当我将所有内容都上传到传输编码分块的网站上时。 尽管请求是合法且正确的,但我无法检索内容。 代码是用Lua编写的,我正在尝试在NodeMCU设备上工作。
conn=net.createConnection(net.TCP, 0)
conn:on("connection",function(conn, payload)
conn:send("GET /mypath/node.php?id=1&update"..
" HTTP/1.1\r\n"..
"Host: www.mydomain.com\r\n"..
"Accept: */*\r\n"..
"User-Agent: Mozilla/4.0 (compatible; esp8266 Lua;)"..
"\r\n\r\n")
end)
conn:on("receive", function(conn, payload)
if string.find(payload, "UPDATE")~=nil then
node.restart()
end
conn:close()
conn = nil
end)
conn:connect(80,"www.mydomain.com")
end
只是要重复此GET请求的工作原理,并在本地主机上对其进行了手动测试。 唯一的问题是分块的内容,我不知道如何解析它。
更新:我设法通过将HTTP / 1.1更改为HTTP / 1.0来删除分块编码,但是仍然有问题
使用此代码
conn:on("receive", function(conn, payload)
print(payload)
我得到这个回应
HTTP/1.1 200 OK
Date: Tue, 09 Jan 2018 02:34:25 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: PHPSESSID=9m226vr20r4baa634bagk8k2k3; path=/
Connection: close
Content-Type: text/html; charset=utf-8
更新2。
我刚刚创建了一个文件“ http.php”,其中包含“ php”。 我已将其上传到本地主机和我的域。 一旦我尝试从nodemcu访问我的本地主机,然后再访问域。 结果不一样
这是要求
conn:send("GET /"..s.path.."/http.php"..
" HTTP/1.0\r\n"..
"Host: "..s.domain.."\r\n"..
"Accept: */*\r\n"..
"User-Agent: Mozilla/4.0 (compatible; esp8266 Lua;)"..
"\r\n\r\n")
end)
s.domain和s.path对应于本地主机和我的域上的不同路径和域
域结果
HTTP/1.1 200 OK
Date: Tue, 09 Jan 2018 03:09:28 GMT
Server: Apache
Connection: close
Content-Type: text/html; charset=UTF-8
在本地主机上的结果
TTP/1.1 200 OK
Date: Tue, 09 Jan 2018 03:08:48 GMT
Server: Apache/2.4.27 (Win64) PHP/7.0.23
X-Powered-By: PHP/7.0.23
Content-Length: 3
Connection: close
Content-Type: text/html; charset=UTF-8
php
如您所见,本地主机显示内容“ php”,而域仅显示标头。 当我键入一些不存在的文件时,域显示给我html代码。
我正在使用以下代码将这些块放在一起。 无论如何,我想知道为什么服务器的响应缺少Content-Length
标头。
conn:on("receive", function(client, payload)
-- Inspired by https://github.com/marcoskirsch/nodemcu-httpserver/blob/master/httpserver.lua
-- Collect data packets until the size of HTTP body meets the Content-Length stated in header
if payload:find("Content%-Length:") or bBodyMissing then
if fullPayload then fullPayload = fullPayload .. payload else fullPayload = payload end
if (tonumber(string.match(fullPayload, "%d+", fullPayload:find("Content%-Length:")+16)) > #fullPayload:sub(fullPayload:find("\r\n\r\n", 1, true)+4, #fullPayload)) then
bBodyMissing = true
return
else
payload = fullPayload
fullPayload, bBodyMissing = nil
end
end
if (bBodyMissing == nil) then
local _, headerEnd = payload:find("\r\n\r\n")
local body = payload:sub(headerEnd + 1)
print (body)
end
end)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.