【问题标题】:Lua send json request bodyLua 发送 json 请求体
【发布时间】:2016-02-01 01:46:57
【问题描述】:

我对 LUA 很陌生,我正在尝试使用 LUA 从我的 ESP8266 向我的本地主机上的 PHP 服务器发送一个 json 帖子,我搜索了互联网,但我找不到任何示例可以帮助我请?

我的 LUA 代码

-- tested on NodeMCU 0.9.5 build 20141222...20150108
-- sends connection time and heap size to http:server.php
wifi.setmode(wifi.STATION)
wifi.sta.config("VIVA-4G-LTE-6134","VIVA176429")
--wifi.sta.config("AndroidAP","rapz4736")

print('httpget.lua started')
Tstart  = tmr.now()

conn = nil
conn = net.createConnection(net.TCP, 0) 

-- show the retrieved web page

conn:on("receive", function(conn, payload) 
                       success = true
                       print(payload) 
                       end) 

-- once connected, request page (send parameters to a php script)

conn:on("connection", function(conn, payload) 
                       print('\nConnected') 
                       conn:send("POST /server.php?"
                        .."name=mometto"
                        .."&age=27"
                        .." HTTP/1.1\r\n" 
                        .."Host: 172.0.0.1\r\n" 
                        .."Connection: close\r\n"
                        .."Accept: */*\r\n" 
                        .."User-Agent: Mozilla/4.0 "
                        .."(compatible; esp8266 Lua; "
                        .."Windows NT 5.1)\r\n" 
                        .."\r\n") 
                   --  conn:send("what":"books", "count":3 )
                       end) 

-- when disconnected, let it be known
conn:on("disconnection", function(conn, payload) print('\nDisconnected') end)

conn:connect(80,'192.168.43.181') 

这里发送参数很容易,但是当我想发送请求正文时我不能,我尝试添加此代码来发送请求正文

conn:send("what":"books", "count":3 )

但它不起作用 我收到这条消息:

那么有谁能帮帮我吗?

【问题讨论】:

  • 什么不完全有效?被注释掉的connection:send 电话?它怎么不工作? send 是把表序列化成 json 还是需要自己做?
  • var superHero 这在我看来是不对的。这是Lua代码? var 不应该在那里,表应该是一个字符串并在 php 端转换为 json
  • ("what":"books", "count":3 ) 同样,这似乎不是有效的 Lua 代码,这在过去是否有效?

标签: php json http lua nodemcu


【解决方案1】:

所以,首先这是字典的无效 Lua 代码。其次,如果你想发送 JSON,你需要使用 cjson 模块对其进行编码。

试试类似的东西

local msg = {"what":"books", "count":3}
conn:send(cjson.encode(msg))

【讨论】:

    猜你喜欢
    • 2011-01-02
    • 2012-08-08
    • 1970-01-01
    • 2014-03-29
    • 2018-02-16
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多