如何在地址之后使用?key = value&key = value进行正确的HTTP Post请求

问题描述:

我自己做一个http.post()请求有问题。 我想在基于ESP8266和Lua语言的NodeMCU上执行API请求。 我遇到的第一个问题是“HTTPS地址上的纯HTTP”。 现在它说“坏的标记”,所以,这意味着他没有收到我的帖子参数。如何在地址之后使用?key = value&key = value进行正确的HTTP Post请求

它是如何正确的?

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) 

通常我使用GMod Lua来提出请求。代码会有简单:

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

http.Post on GMod Lua Wiki

================== 更新。我做了我自己的代码。

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 

但现在我有新的问题: 一些API的请求只有HTTPS连接。

+0

该内容类型不是文本/纯文本。 –

+0

这可以被认为是解决? –

你没有给我们一个URL来验证(我知道这将是很难的)。因此,未经检验的正确的代码会是这样:

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) 

确保您{token=mytokenhere,arg1=argumentforrequest}是通过验证有效的JSON例如jsonlint.com。

如果遇到HTTPS问题,那么这可能是https://github.com/nodemcu/nodemcu-firmware/issues/1707

+0

您的解决方案无法正常工作。 {“status”:“NO”,“message”:“坏令牌”} - 这意味着该网站没有收到任何参数。我用自己的命令解决了这个问题 – Spar

+0

“让我自己的命令” - 这是什么意思?我的代码的正确性很容易通过运行http://httpbin.org/post来验证。 –

+0

我更新问题 – Spar