我将 copas 库用于非阻塞请求。我遇到了一个问题。我无法理解如何传递以下标头:“Content-Type: application/json”,而且我还想在 POST 和 GET 方法之间切换,怎么做?
我的代码:
功能:
function httpRequest(request, body, handler)
if not copas.running then
copas.running = true
lua_thread.create(function()
wait(0)
while not copas.finished() do
local ok, err = copas.step(0)
if ok == nil then error(err) end
wait(0)
end
copas.running = false
end)
end
-- do request
if handler then
return copas.addthread(function(r, b, h)
copas.setErrorHandler(function(err) h(nil, err) end)
h(http.request(r, b))
end, request, body, handler)
else
local results
local thread = copas.addthread(function(r, b)
copas.setErrorHandler(function(err) results = {nil, err} end)
results = table.pack(http.request(r, b))
end, request, body)
while coroutine.status(thread) ~= 'dead' do wait(0) end
return table.unpack(results)
end
end
使用示例:
httpRequest("https://sampmulti.azurewebsites.net/get/last_message", nil, function(response, code, headers, status)
if response then
local data = json.decode(response)
last_message= data["last_message"]
print("last_message: ", last_message)
else
print('Error', code)
end
end)
如何仅对标头和方法 POST 或 GET 执行相同操作?
我也阅读了文档,但不明白如何做到这一点。 https://keplerproject.github.io/copas/manual.html