【问题标题】:How to make correct HTTP Post request with ?key=value&key=value after the adress如何在地址后使用 ?key=value key=value 发出正确的 HTTP Post 请求
【发布时间】:2018-02-26 00:08:39
【问题描述】:

我自己执行 http.post() 请求时遇到问题。 我想使用 Lua 语言在基于 ESP8266 的 NodeMCU 上执行 API 请求。 我遇到的第一个问题是“HTTPS 地址上的纯 HTTP”。 现在它说“bad token”,所以,这意味着他没有收到我的帖子参数。

如何正确?

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 连接。

【问题讨论】:

  • 该内容类型不是文本/纯文本。
  • 这算是解决了吗?

标签: http lua esp8266 nodemcu


【解决方案1】:

你没有给我们一个 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

【讨论】:

  • 您的解决方案无效。 {"status":"NO","message":"bad token"} -- 这意味着该站点没有收到任何参数。我通过制定自己的命令来解决问题
  • “让我自己指挥”——这是什么意思?我的代码的正确性可以通过在httpbin.org/post 上运行来轻松验证。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 2013-03-23
  • 2015-10-12
  • 2015-03-22
相关资源
最近更新 更多