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

我正在尝试使用http.post()请求API接口,并在基于ESP8266的NodeMCU上使用Lua语言。但是我遇到了一个问题:“在HTTPS地址上使用纯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请求失败")
  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)

GMod Lua Wiki中的http.Post

================== 更新:我已经编写了自己的代码。

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

点赞
用户131929
用户131929

你没有给我们一个能够验证的 URL (因为 token 的原因可能很难)。因此,未经测试的正确代码应该是这样的:

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 请求失败")
    else
      print(code, data)
    end
  end)

请确保你的 {token=mytokenhere,arg1=argumentforrequest} 在验证后是有效的 JSON,例如可以使用 jsonlint.com 进行验证。

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

2017-09-18 19:38:20