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

问题描述

我已经尝试了几个小时来向一个简单的页面发出 GET 请求,然后作为结果获取正文,但 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

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

解决方法

如果您使用 get 中的 luvit/http,那么在回调中,您会在获得标头时尽早获得 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)