Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua : Fetch a webpage

I want to fetch a webpage and get the result in a string, but I don't know how to do it. I search online and didn't find how to do it.

like image 353
luanoob Avatar asked Jul 28 '11 11:07

luanoob


3 Answers

I'd simply use Lua Socket which comes with an http submodule. You can simply use http.request to get a webpage into whatever container you'd want (default is string, but you can use a table, a file, stdio, ... using ltn12 filters and sinks).

As an example:

local http=require'socket.http'
local body, statusCode, headers, statusText = http.request('http://w3.impa.br/~diego/software/luasocket/http.html')
print('statusCode ', statusCode)
print('statusText ', statusText)
print('headers ')
for index,value in pairs(headers) do
    print("\t",index, value)
end
print('body',body)
like image 131
jpjacobs Avatar answered Nov 04 '22 01:11

jpjacobs


If you can't find an exact http client library, you could implement on yourself, or build on someone else's work.

In that link, although it is called libhttpd, but the author clearly states that it can be used for anything. Looks like a more usable wrapper around lua sockets.

like image 38
Moo-Juice Avatar answered Nov 03 '22 23:11

Moo-Juice


if you don't have socket (like me), but you have the http library/module, then you could try this:

http.get("https://nodemcu.readthedocs.io/en/master/en/modules/http/", nil, function(code, data)
    if (code ~= 200) then
        print("HTTP request failed")
    else
        print(code, data)
    end
end)

it works for me

you can find more info in the docs https://nodemcu.readthedocs.io/en/master/en/modules/http/#httpget

like image 1
Joe Black Avatar answered Nov 04 '22 00:11

Joe Black