简体   繁体   中英

Lua send json request body

i am very new to LUA and i am trying to send a json post from my ESP8266 using LUA to a PHP server on my localhost, i searched the internet and i cant find any example to do that can any one help me please ?

my LUA code

-- 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') 

here it is easy for me to send parameters, but when i want to send a request body i cant, i tried to add this code to send the request body

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

but it is not working and i get this message : 在此处输入图片说明

so can any one provide any help for me please ?

So, firstly that's invalid Lua code for a dictionary. Secondly, if you want to send JSON, you're going to need to encode it with the cjson module.

Try something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM