使用系统代理进行Web请求的Luasocket替代方案

我已经有两个关于Lua和Web请求的问题,但我仍然在挣扎。

我仍然需要通过URL下载文件,多亏了Paul Kulchenko,我找出了我最初失败的主要原因:我所在的企业网络阻止了传出请求,可能是一个DMZ、防火墙或公司使用的其他东西。使用公司代理之一应该解决我的问题,但并没有。

以下是我正在使用的代码:

-- retrieve the content of a URL
local socket = require("socket")
local http = require("socket.http")
local inspect = require("inspect")
--http.PROXY = "http://my.company.proxy.com:8080"
--http.PROXY = "http://my.company.proxy.com:8080"
--http.PROXY = "http://my.company.proxy.com:8080"
http.PROXY = "http://my.company.proxy.com:8080"
local body, code = http.request("http://pbs.twimg.com/media/CCROQ8vUEAEgFke.jpg")
print(inspect(code))
if not body then error(code) end

-- save the content to a file
local f = assert(io.open('test.jpg', 'wb'))
f:write(body)
f:close()

使用上述代码时,我会出现不同的错误,但仍然是错误..

local http = require("socket.http")
local socket = require("socket")
local inspect = require("inspect")
require("show")
require("ltn12")
local ResFileStr = "CCROQ8vUEAEgFke.jpg"
local PathStr = "http://pbs.twimg.com/media/"
local ResHnd, ErrStr = io.open(ResFileStr, "wb")
if ResHnd then
  local Req = {
  url = PathStr .. ResFileStr,
  sink = ltn12.sink.file(ResHnd),
  --proxy = "http://my.company.proxy.com:8080"
  --proxy = "http://my.company.proxy.com:8080"
  --proxy = "http://my.company.proxy.com:8080"
  --proxy = "http://my.company.proxy.com:8080"
  proxy = "http://my.company.proxy.com:8080"
  }
  local Response = {http.request(Req)}
  ObjectShow(Response, "Response")
  print(inspect(Response))
else
io.write("Error opening ", ResFileStr, " for writing\n")
end

我得到的错误要么是500域名未找到,要么是404未找到。

当我使用Microsoft的.NET框架和System.net.WebClient类时,下载文件或访问网站都没有问题。不幸的是,我不知道Microsoft的类做了什么不同,所以我猜它是更高级的代码使用我的系统设置为代理。

因此,我的问题是:除了Luasocket之外,是否有类似的“高级”库或其他库可以使用?我看了一眼libcurl、luacurl,但它们似乎比luasocket更复杂。还是说我能用lua得到这个工作?或者我的lua方法完全错误?

附:inspect是kikito的库(可在github上找到用于调试),而show只是这个脚本和这个函数

点赞
用户2328287
用户2328287

你可以尝试使用Lua-cURL库。

因为我没有代理,所以代码未经测试

local cURL = require "cURL"

local f = assert(io.open('test.jpg', 'wb'))

cURL.easy{
  url           = "http://pbs.twimg.com/media/CCROQ8vUEAEgFke.jpg",
  proxy         = "http://my.company.proxy.com:8080",
  writefunction = f
}
:perform()
:close()

f:close()
2015-04-17 19:06:26