Сopas. 使用请求中的头部信息并选择请求方法
2020-7-17 16:19:34
收藏:0
阅读:140
评论:1
我正在使用 copas 库进行非阻塞请求。 我遇到了一个问题。我不知道如何传递以下头部信息:"Content-Type: application/json",我也想在 POST 和 GET 方法之间进行切换,该如何实现?
我的代码:
function:
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
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

copas.http请求应该与LuaSocket的http请求兼容(http://w3.impa.br/%7Ediego/software/luasocket/http.html#request)。
尝试下面的示例,使用自定义标题将POST发送到httpbin.org:
local copas = require "copas" local http = require "copas.http" local ltn12 = require "ltn12" -- 需要处理流 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()