This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Reciprocaterman's profile picture

Having problems using HTTP api

Started by Reciprocaterman, 29 March 2014 - 05:38 PM
Reciprocaterman #1
Posted 29 March 2014 - 06:38 PM
I'm having an issue with getting a real world date. The code below is basically what I'm using.

local date_url = "http://www.timeapi.org/utc/now?\m/\d/\Y"

local function getDate()
	   request = http.get(date_url)
	   date = request:readAll()
	   request.close()
	   print(date) --Debugging
	   return date
end

The problem is it should return something like "03/29/2014" instead it returns "m/d/Y" Just looking towards the more knowledgeable to help me figure this out.
Edited on 29 March 2014 - 10:29 PM
nateracecar5 #2
Posted 30 March 2014 - 10:23 PM
I checked this out, and used both http.request and http.get. I have a feeling it's something to do with lua, or the timeapi server. It's not you I presume. :)/>
Reciprocaterman #3
Posted 03 April 2014 - 02:02 PM
Good news after a little messing around I got it to work, only changed 1 little thing in the code.

local date_url = "http://www.timeapi.org/utc/now?format=%20%25D"

local function getDate()
   request = http.get(date_url)
   date = request:readAll()
   request.close()
   print(date) --debugging
   return date
end

It now returns 04/03/2014

It seems it was a problem with my formatting itself, while the two are equivalent this is the one that worked.
TheOddByte #4
Posted 03 April 2014 - 06:39 PM
One thing that you should do when using the http api is this

local function getDate()
    local request = http.get( date_url )
    if request then
        local date = request.readAll()
        request.close()
        return date
    else
        request.close()
        return nil
    end
end
As you may notice above it returns the date if server is responding, Else it returns nil.
This is always good to check if it is responding or not, Ofcourse with your code it would still return nil, But this way can be useful when returning booleans.
So for example you want to use http.get on google or something just to check that you have an internet connection that isn't totally slow you could just do this

local function test()
    local response = http.get( "http://www.google.com" )
    if response then
        return true
    else
        return false
    end
end

local foo = test()
if foo then
    print( "bar" )
else
    print( "Google isn't responding" )
end