1

我有一个具有 JSON API 的 Django,我希望它能够在我的 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
}

post method我在for jsonin 中有问题Lua。我希望返回的 json 将在 Lua 中获取。

我在我的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 传递。我的问题是像这个 CURL 这样的等效代码是什么

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

在 Lua(Corona SDK)中,以便 Lua 可以获取并下载返回的Json? 我的代码Lua是正确的吗?

有人知道我的案子吗?提前致谢 ...

4

1 回答 1

1

为什么不使用 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

编辑

如果你真的想使用 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-29T04:16:45.137 回答