There is a problem when you attempt to return a value from a function that requires a response from network.request(). The problem is that the result returned will be nil. Only after some time has passed will the result from the network.request() be available. You can use the network listener to wait for the response, but there is no obvious way to return that response to a calling function. I am submitting this as a bug because the same problem does not occur when using Lua sockets. I am including sample code for each (network.request() and http.request()) situation so you can see the difference.
network.request() sample code:
local myText = display.newText("(Waiting for response)", 0, 0, native.systemFont, 16)
myText.x = display.contentCenterX
myText.y = 120
local result = ""
local function getHTML()
local function networkListener( event )
if ( event.isError ) then
myText.text = "Network error!"
else
myText.text = "See Corona Terminal for response"
print ( "RESPONSE: " .. event.response )
return event.response
end
end
network.request( "http://www.brainjar.com/java/host/test.html", "GET", networkListener )
end
result = getHTML()
print ("result: "..result)
lua sockets sample code:
local http = require("socket.http")
local ltn12 = require("ltn12")
local myText = display.newText("(Waiting for response)", 0, 0, native.systemFont, 16)
myText.x = display.contentCenterX
myText.y = 120
local results = ""
local function getHTML()
local r,c,h
local response = {}
-- Request remote file and save data to local file
r,c,h = http.request{
url = "http://www.brainjar.com/java/host/test.html",
sink = ltn12.sink.table(response),
}
myText.text = "See Corona Terminal for response"
return table.concat(response,"")
end
result = getHTML()
print("result: "..result)
[import]uid: 104085 topic_id: 34371 reply_id: 334371[/import]