Fetching page of url using luasocket and proxy

有些话、适合烂在心里 提交于 2019-12-01 05:54:29

You are using the 'generic' form of http.request(), which requires storing the body via a LTN12 sink. It's not as complicated as it sounds, try this code:

local socket = require "socket.http"
local ltn12 = require "ltn12"; -- LTN12 lib provided by LuaSocket

-- This table will store the body (possibly in multiple chunks):
local result_table = {};
client,r,c,h = socket.request{
    url = "http://example.com/",
    sink = ltn12.sink.table(result_table),
    proxy="<my proxy and port here>"
}
-- Join the chunks together into a string:
local result = table.concat(result_table);
-- Hacky solution to extract the title:
local title = result:match("<[Tt][Ii][Tt][Ll][Ee]>([^<]*)<");
print(title);

If your proxy is constant throughout your application then a more straightforward solution would be to use the simple form of http.request(), and specify the proxy via http.PROXY:

local http = require "socket.http"
http.PROXY="<my proxy and port here>"

local result = http.request("http://www.youtube.com/watch?v=_eT40eV7OiI")
local title = result:match("<[Tt][Ii][Tt][Ll][Ee]>([^<]*)<");
print(title);

Output:

    Flanders and Swann - A song of the weather
  - YouTube
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!