使用Lua执行HTTP POST请求。

我已经编写了一个 Python 脚本,它将数据 POST 到一个 Apache Web 服务器,并且数据很好地存储在 $_POST 和 $_FILES 数组中。现在我想将同样的事情在 Lua 中实现,但我还无法让它正常运行。

我的 Python 代码大致如下:

    try:
        wakeup()
        socket.setdefaulttimeout(TIMEOUT)
        opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
        host = HOST
        func = "post_img"
        url = "http://{0}{1}?f={2}&nodemac={3}&time={4}".format(host, URI, func, nodemac, timestamp)
        if os.path.isfile(filename):
            data = {"data":open(filename,"rb")}
            print "POST time "+str(time.time())
            response = opener.open(url, data, timeout=TIMEOUT)
            retval = response.read()
            if "SUCCESS" in retval:
                return 0
            else:
                print "RETVAL: "+retval
                return 99
    except Exception as e:
        print "EXCEPTION time "+str(time.time())+" - "+str(e)
        return 99

我目前编写的 Lua 代码如下:

#! /usr/bin/lua

http = require("socket.http")
ltn12 = require("ltn12")

http.request{
    url = "localhost/test.php?test=SEMIOS",
    method = "POST",
    headers = {
        ["Content-Type"] =  "multipart/form-data; boundary=127.0.1.1.1000.17560.1375897994.242.1",
        ["Content-Length"] = 7333
    },
    source = ltn12.source.file(io.open("test.gif")),
    sink = ltn12.sink.table(response_body)
}
print(response_body[1]) --response to request

但是当我执行这段代码时,它一直告诉我:

$ ./post.lua
/usr/bin/lua: ./post.lua:17: attempt to index global 'response_body' (a nil value)
stack traceback:
        ./post.lua:17: in main chunk
        [C]: ?
reg@DesktopOffice:~$
点赞
用户1442917
用户1442917

以下是 Lua 发送 POST 数据的几个例子:来自 luasocket 作者SO这个例子 直接与文件交互,与你所使用的非常接近。

您提供的问题描述与您提供的评论不符。

2013-08-07 23:47:35