首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Сopas。在请求中传入头部,并选择请求方法

Сopas。在请求中传入头部,并选择请求方法
EN

Stack Overflow用户
提问于 2020-07-18 00:19:34
回答 1查看 83关注 0票数 0

我使用copas库来处理非阻塞请求。我遇到了一个问题。我不能理解如何传递下面的头:“Content-Type:application/json”,而且我还想在POST和GET方法之间切换,该怎么做呢?

我的代码:

功能:

代码语言:javascript
复制
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

使用示例:

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-05 05:33:08

copas.http请求应与LuaSocket http request兼容

尝试下面的示例,它将使用一些自定义标头向httpbin.org发出POST:

代码语言:javascript
复制
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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62958007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档