用Lua执行http post

时间:2013-08-06 21:32:03

标签: python http post lua http-headers

我编写了一个Python脚本,将数据发送到apache webserver,数据很好地到达$ _POST和$ _FILES aray。现在我想在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:~$ 

1 个答案:

答案 0 :(得分:1)

有几个使用Lua发送POST数据的示例:from the author of luasocketSOThis example直接与文件一起使用,这与您正在使用的文件非常接近。

您对此问题的描述与comment you provided不符。