1

This is my first time here and thought of joining the forum because I am new to Lua programming and have almost given up on HTTP Post method.

I am trying my hands on IOT using ESP8266 (running on NodeMCU) and using ESPlore to send the Lua program to ESP8266.

So, my program's objective is to call an API and post few parameters using my Lua program running on ESP8266.

I tried the following approaches -

1. Using 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 as below ----------------------------------------------------

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

----------------Response --------------------------------------

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 - Error report
The request sent by the client was syntactically incorrect.

I don't understand what is wrong with it.

2. Using Luasocket

I have included following in my program -

local http = require"socket.http"
local ltn12 = require"ltn12"

and it throws following errors-

script1.lua:3: module 'socket.http' not found:
no field package.preload['socket.http']
no file 'socket/http.lc'
no file 'socket/http.lua'

I don't know how to get these libs and send to ESP8266 and not sure if that will suffice.


Question :

Which is the best method to post data to a server using an API.
a. If HTTP Post, what is the problem with my code.
b. If Luasocket then how do I send it to ESP8266 as I am not using a compiler on my laptop.

Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
DroidGamer
  • 11
  • 1
  • 3

1 Answers1

0

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

I don't understand what is wrong with it.

In HTTP,the headers are always delimited by \r\n\r\n. Without the second CR-LF pair, the following data with cause a header error as reported dy Tomcat.

Second you can't use the standard socket libraries on the ESP8266. You must use the net library which is a nodemcu wrapper around the Espressif SDK.

Community
  • 1
  • 1
TerryE
  • 10,724
  • 5
  • 26
  • 48