-3

I have a problem with doing by myself a http.post() request. I want to perform API requests on NodeMCU based on ESP8266 with Lua language. The first problem that i met was "Plain HTTP on HTTPS adress". For now it says "bad token", so, it means that he didn't receive my post parameters.

How it need to be correct?

http.post("http://www.2level.1level/api.php","Content-Type: text/plain","token=mytokenhere&arg1=argumentforrequest",
  function(code, data)
    if (code < 0) then
    print("HTTP request failed")
  else
    print(code, data)
  end
end)

Usually i use GMod Lua for making requests. Code there will be easy:

http.Post("https://www.2level.1level/api.php",{token=mytokenhere,arg1=argumentforrequest},function(txt) end,function(txt) end)

http.Post on GMod Lua Wiki

================== Update. I made my own code.

function ghttp.Post(url, parameters, onSuccess, onFailure, headers)
    local add = ""
    if parameters then
        local temp = {}
        for k,v in pairs(parameters) do
               table.insert(temp,ghttp.encode(k).."="..ghttp.encode(v))
        end
        add = "?"..table.concat(temp, "&")
    end
    http.post(url..add,"Content-Type: application/json\r\n"..(headers or ""),"",function(code, data)
         if (code < 0) then
             if onFailure then onFailure() end
          else
                  if onSuccess then onSuccess(code,data) end
          end
     end)
end

But now i have new problem: Some API's request only HTTPs connection.

Spar
  • 1,582
  • 9
  • 16

1 Answers1

0

You didn't give us a URL to verify (would be hard because of the token, I know). So, untested the correct code would be like this:

http.post('https://www.2level.1level/api.php',
  'Content-Type: application/json\r\n',
  '{token=mytokenhere,arg1=argumentforrequest}',
  function(code, data)
    if (code < 0) then
      print("HTTP request failed")
    else
      print(code, data)
    end
  end)

Make sure your {token=mytokenhere,arg1=argumentforrequest} is valid JSON by verifying with e.g. jsonlint.com.

In case you run into problems with HTTPS then this might be https://github.com/nodemcu/nodemcu-firmware/issues/1707.

Marcel Stör
  • 22,695
  • 19
  • 92
  • 198
  • Your solution didn't work. {"status":"NO","message":"bad token"} -- It means the site didn't receive any args. I solve the problem by making me own command – Spar Sep 25 '17 at 16:04
  • "making me own command" - what does that mean? The correctness of my code can easily be verified by running it against http://httpbin.org/post. – Marcel Stör Sep 25 '17 at 18:50