NodeMCU - Lua - HTTP Post或luasocket - 需要指导

问题描述 投票:1回答:1

这是我第一次来到这里,并考虑加入论坛,因为我是Lua编程的新手,几乎放弃了HTTP Post方法。

我正在尝试使用ESP8266(在NodeMCU上运行)并使用ESPlore将Lua程序发送到ESP8266。

所以,我的程序的目标是使用我在ESP8266上运行的Lua程序调用API并发布一些参数。

我尝试了以下方法 -

1.使用HTTP Post

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&param2=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,因为我没有在我的笔记本电脑上使用编译器。

lua http-post luasocket esp8266 nodemcu
1个回答
0
投票

"Content-Type: application/x-www-form-urlencoded\r\n"..data

我不明白它有什么问题。

在HTTP中,标题始终由\r\n\r\n分隔。如果没有第二个CR-LF对,则以下数据会导致报头dy Tomcat出现报头错误。

其次,您无法在ESP8266上使用标准套接字库。您必须使用网络库,它是Espressif SDK周围的nodemcu包装器。

© www.soinside.com 2019 - 2024. All rights reserved.