如何使用 Luvit HTTPS 执行简单的 GET 请求

我已经尝试了几个小时,试图向一个简单的页面发起 GET 请求,然后获取其响应的 body,但是 Luvit 让这个过程变得非常复杂。

function httpGET()
    request = networking.get("https://google.com")
    local function callback(param)
      print(param)
    end
    request:done(callback)
end

经过多次尝试,以下是我最接近的方式(使用此库https://github.com/cyrilis/luvit-request

如果有更多经验的人可以编写一个简单的函数来获取页面的正文内容,我将不胜感激。谢谢!

点赞
用户12918181
用户12918181

如果您正在使用 luvit/httpget 函数,那么在回调中您会获得 IncomingMessage 对象,早在您获得头部信息时,您必须自行解释 data 事件。

local http,https = require('http'),require('https')

function httpGET(url, callback)
    url = http.parseUrl(url)
    local req = (url.protocol == 'https' and https or http).get(url, function(res)
      local body={}
      res:on('data', function(s)
        body[#body+1] = s
      end)
      res:on('end', function()
        res.body = table.concat(body)
        callback(res)
      end)
      res:on('error', function(err)
        callback(res, err)
      end)
    end)
    req:on('error', function(err)
      callback(nil, err)
    end)
end

httpGET('http://example.com', function(res,err)
  if err then
    print('error', err)
  else
    print(res.body)
  end
end)
2021-03-26 09:17:10