Lua的等效CURL,(Django API Json转换为Lua Json)POST方法。

我有一个Django项目,在其中有用于JSON的API,我希望在我的Lua(Corona SDK)项目中获取它。

如果我使用 CURL 请求我的Django项目:

curl -l -X POST -d "message=getstrings" http://127.0.0.1:8000/api/getstrings/

这将返回以下内容:

{
    "message": "Something good happened on the server!",
    "data": [
        {
            "code": "003",
            "doc1": "sd.doc",
            "title": "Test",
            "artist": "ABBA",
            "img": "sd.png",
            "genre": "Pop"
        },
        {
            "code": "004",
            "doc1": "sdsd.doc",
            "title": "sdf",
            "artist": "ABBA",
            "img": "sdsd.png",
            "genre": "Pop"
        }
    ],
    "success": true
}

我有一个使用Luapost方法json问题。我希望获取Lua中返回的JSON。

我在我的Lua中尝试以下代码:

local response = {}
local r, c, h = http.request{
  url= "http://127.0.0.1:8000/api/getstrings/",
  method = "POST",
  headers = {
    ["content-length"] = "",
    ["Content-Type"] = "application/x-www-form-urlencoded"
  },
  source = ltn12.source.string(post),
  sink = ltn12.sink.table(response)
}
local path = system.pathForFile("r.txt", system.DocumentsDirectory)
local file = io.open (path, "w")

file:write (response[1] .. "\n")
io.close (file)

当我打开 r.txt 文件时,我得到以下错误信息:

File "home/myhome/workspace/djangoproj/api/handlers.py", line 21, in create
  if attrs['message'] == 'getstrings':

KeyError: 'message'

我知道错误的原因在于message及其值没有被Lua传递。我的问题是在Lua中等效于这个CURL命令:

curl -l -X POST -d "message=getstrings" http://127.0.0.1:8000/api/getstrings/

这样Lua就可以下载返回的JSON了? 我的代码是否正确?有谁能帮我解决这个问题吗?感谢您的帮助。

点赞
用户1137788
用户1137788

为什么不使用 Corona 提供的 network.request 函数呢?它也是异步的。

local function listener(event)
    print(event.response)
    print(event.isError)
    print(event.status)
end

local url = "http://127.0.0.1:8000/api/getstrings/"

local body = "message=getstrings"

local headers = {}
headers["content-length"] = body:len(),
headers["Content-Type"] = "application/x-www-form-urlencoded"

local postData = {}
postData.body = body
postData.headers = headers

network.request(url,"POST",listener,postData)

在这里阅读更多信息: http://developer.anscamobile.com/reference/index/networkrequest

EDIT

如果你真的想使用 http.request,那么你可以这样做。

local url = "http://127.0.0.1:8000/api/getstrings/"
local body = "message=getstrings"
local headers = {
    ["content-length"] = body:len(),
    ["Content-Type"] = "application/x-www-form-urlencoded"
  }

local response = {}
local r, c, h = http.request{
  url= url,
  method = "POST",
  headers = headers,
  source = ltn12.source.string(body),
  sink = ltn12.sink.table(response)

}
2012-05-29 04:16:45