http - Сopas。在请求中传递标头并选择请求方法
问题描述
我将 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
解决方案
copas.http 请求应该与LuaSocket http 请求兼容
尝试以下示例,该示例将使用一些自定义标头对 httpbin.org 进行 POST:
local copas = require "copas"
local http = require "copas.http"
local ltn12 = require "ltn12" -- needed to process the streams
function doRequest()
local reqbody = "isThisAGreatExample=true"
local respbody = {}
local ok, code, headers, status = http.request {
method = "POST",
url = "https://httpbin.org/post",
source = ltn12.source.string(reqbody),
headers =
{
["Accept"] = "*/*",
["Accept-Encoding"] = "gzip, deflate",
["Accept-Language"] = "en-us",
["Content-Type"] = "application/x-www-form-urlencoded",
["content-length"] = string.len(reqbody)
},
sink = ltn12.sink.table(respbody)
}
print('ok:' .. tostring(ok))
print('code:' .. tostring(code))
print('body:' .. table.concat(respbody))
end
copas.addthread(doRequest)
copas.loop()
推荐阅读
- python - 计算数组中的笑脸。如果在数组问题
- common-lisp - How come (let ((x 'huh?)) (cons (boundp 'x) x)) evaluates to (NIL . HUH?)?
- python - 在液晶显示器上写更多行会使程序无法正常工作
- modelsim - 设置为使用 Modelsim 时如何忽略 VUnit 中的文件?
- php - 表单提交后在选择项目中设置默认选定标签
- javascript - React JS材料表根据其他两列的值自动生成一列的值
- c# - 通过 SSL 调用 Web Api 时出现 403 禁止错误
- java - 我正在尝试从 Jenkins Pipeline 生成 Allure 报告,但遇到错误
- php - 如何使用php创建换行符
- php - 在 Laravel 中提交表单后如何重定向到主页