NodeMCU HTTP 模块 HTTP.POST() 请求正文参数

请问有人能告诉我如何编写http.post()请求的正文,以读取ESP8266上附加传感器的值吗?

wifi.setmode(wifi.STATION);
wifi.sta.config("ssid","pwd")
local sensorPin = adc.read(0)

http.post('url',
  'Content-Type: application/json\r\n',
  '"humidity":sensorPin'
  ,function(code, data)
    if (code < 0) then
      print("HTTP request failed")
    else
      print(code, data)
    end
  end)

如何从GPIO引脚上的附加传感器读取值,并将其作为post请求正文中"key":"value"对的值?

点赞
用户131929
用户131929

抱歉,我不明白您的问题是什么。您是想了解如何读取GPIO值,还是处理ADC,或者是定时发送数据,还是在Lua中进行字符串拼接,还是其他问题?

因此,这里有一段短代码片段可修复您的代码:

url = 'url'
jsonContentTypeHeader = 'Content-Type: application/json\r\n'

http.post(url, jsonContentTypeHeader,
  '{"humidity":' .. adc.read(0) .. '}', function(code, data)
    if (code < 0) then
      print("HTTP request failed")
    else
      print(code, data)
    end
  end)

如果您需要编码更多的JSON数据,那么有一个专门的模块可用于此。

值得注意的是, wifi.sta.config(“ssid”、“pwd”)是异步的(许多NodeMCU函数也是如此),并且您需要等待到获取到IP地址再进行网络调用。我们在文档中还有一个该模板

2017-04-11 05:34:59