【发布时间】:2016-01-09 03:16:27
【问题描述】:
这是我第一次来这里并想到加入论坛,因为我是 Lua 编程的新手,几乎已经放弃了 HTTP Post 方法。
我正在尝试使用 ESP8266(在 NodeMCU 上运行)并使用 ESPlore 将 Lua 程序发送到 ESP8266 进行 IOT。
所以,我的程序的目标是使用在 ESP8266 上运行的 Lua 程序调用 API 并发布一些参数。
我尝试了以下方法 -
1.使用 HTTP 发布
conn=net.createConnection(net.TCP, 0)
conn:on("receive", display)
conn:connect(80,HOST)
conn:on("connection",function(obj)
local post_request = build_post_request(HOST,URI)
obj:send(post_request)
end
----功能如下---------------------------------------- ------------
function build_post_request(host, uri)
local data = ""
data = "param1=1¶m2=2"
request = "POST uri HTTP/1.1\r\n"..
"Host: example.com\r\n"..
"apiKey: e2sss3af-9ssd-43b0-bfdd-24a1dssssc46\r\n"..
"Cache-Control: no-cache\r\n"..
"Content-Type: application/x-www-form-urlencoded\r\n"..data
return request
end
----------------响应 ------------------------------ --------
HTTP/1.1 400 Bad Request
Date: Sun, 11 Oct 2015 16:10:55 GMT
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 968
Connection: close
Apache Tomcat/7.0.54 - 错误报告
客户端发送的请求语法错误。
我不明白它有什么问题。
2.使用 Luasocket
我的程序中包含以下内容 -
local http = require"socket.http"
local ltn12 = require"ltn12"
它会引发以下错误-
script1.lua:3: module 'socket.http' not found:
no field package.preload['socket.http']
no file 'socket/http.lc'
no file 'socket/http.lua'
我不知道如何获取这些库并将其发送到 ESP8266,但不确定这是否足够。
问题:
使用 API 将数据发布到服务器的最佳方法是什么。
一种。如果是 HTTP Post,我的代码有什么问题。
湾。如果是 Luasocket,那么我如何将它发送到 ESP8266,因为我没有在我的笔记本电脑上使用编译器。
【问题讨论】:
-
一个额外的
\r\n应该放在POST请求头和POST请求数据之间。 -
必须在函数
build_post_request中插入参数uri而不是字符串“uri”。论据host也是如此。 -
嗨,Egor,添加额外的 \r\n,没有帮助,得到相同的响应 - 400 Bad Request(客户端发送的请求在语法上不正确)。
-
在函数 build_post_request 中,我有 HOST 和 URI 值,只是没有复制到这里
标签: lua http-post luasocket esp8266 nodemcu