HTTP API

Functionhttp.checkURL
Determine whether a URL is valid and is whitelisted, meaning the HTTP API can connect to it.
Syntax http.checkURL(
  • url : string
)
Returns boolean true | boolean false, string error
Part of CC:Tweaked (source)
API http
See also http.checkURLAsync
ExampleCheck whether a URL can be visited
Tests whether a remote and local URL is whitelisted
Code
<nowiki>
-- Check against a remote address
print(http.checkURL("https://example.computercraft.cc/"))
-- Check against a local address
print(http.checkURL("https://localhost"))
    </nowiki>
Output
<nowiki>
true
false Domain not permitted
</nowiki>
Functionhttp.checkURLAsync
An asynchronous version of http.checkURL. Determines whether a URL is valid and is whitelisted, meaning the HTTP API can connect to it.
Syntax http.checkURLAsync(
  • url : string
)
Returns boolean true | boolean false, string error
Part of CC:Tweaked (source)
API http
See also http.checkURL
ExampleCheck whether a URL can be visited
Tests whether a remote and local URL is whitelisted
Code
<nowiki>
local checkURL = "https://example.computercraft.cc/"
local ok, err = http.checkURLAsync(checkURL)
if not ok then 
  printError(err)
else
  while true do
    local event, url, ok, err = os.pullEvent("http_check")
    if url == checkURL then
      if not ok then printError(err) end
      break
    end
  end
end
    </nowiki>
Output Nothing, as long as https://example.com.computercraft.cc is whitelisted.
Functionhttp.get
Attempt to fetch a webpage, using the same arguments as http.request. This will return the response table or false, an error message and (optionally) a handle with the failing response’s content. The HTTP API assumes Unicode by default, meaning you may run into issues when fetching binary data. To avoid this, set binary to true. You will have to pass something to headers to set the binary flag, however just passing nil will work fine, e.g. http.get(url, nil, true).
Syntax http.get(
  • url : string
  • headers? : table
  • binary? : boolean
)
Returns table response | boolean false, string error[, table response]
Part of CC:Tweaked (source)
API http
See also http.post, http.request
ExampleDownloading a page
Requests a single page and prints the contents.
Code
<nowiki>
-- Make a HTTP request
local request, err = http.get("https://example.computercraft.cc")
if not request then error(err) end
-- Print the contents
print(request.readAll())
request.close() -- Don't forget to close!
    </nowiki>
Output Prints HTTP is working!
ExampleDownloading binary data
Requests a binary page
Code
<nowiki>
-- Make a HTTP request
local request, err = http.get("https://example.computercraft.cc/logo.gif", nil, true) -- Set binary mode to true
if not request then error(err) end
-- Write the binary data to the file
local file = fs.open("logo.gif", "wb") -- Open the file in binary mode
file.write(request.readAll())
file.close() -- Close the file to save it
request.close() -- Close the HTTP request too, now that we are done with it
    </nowiki>
Functionhttp.post
Attempt to fetch a webpage using the POST method, using the same arguments as http.request. This will return the response table or false, an error message and (sometimes) a handle with the failing response’s content (specifically, this is included when the actual request succeeded, but the server returned an erroneous HTTP code, e.g. 401: Unauthorized). The HTTP API assumes Unicode by default, meaning you may run into issues when fetching binary data. To avoid this, set binary to true. You will have to pass something to postData and headers to set the binary flag, e.g. http.post(url, "", nil, true).
Syntax http.post(
  • url : string
  • postData : string
  • headers? : table
  • binary? : boolean
)
Returns table response | boolean false, string error[, table response]
Part of CC:Tweaked (source)
API http
See also http.get, http.request
ExampleDownloading a page
Requests a single page with some postdata and prints the contents.
Code
<nowiki>
-- Make a HTTP request
local request, err = http.post("https://example.computercraft.cc/post", "test=data&one=two")
if not request then error(err) end
-- Print the contents
print(request.readAll())
request.close() -- Don't forget to close!
    </nowiki>
Output Prints test=data&one=two
Functionhttp.request
Asynchronously submit a HTTP GET request. Unlike http.get and http.post, this will not halt the program flow, which allows it to respond to other events while receiving the HTTP response.

If postData is specified, a POST request is submitted with the specified postData as the body.

Unlike http.get and http.post, the handle is provided via the http_success and http_failure events, which need to be listened for.
Syntax http.request(
  • url : string
  • postData? : string
  • headers? : table
  • binary? : boolean
)
Returns nil
Part of CC:Tweaked (source) (source)
API http
See also http.get, http.post
ExampleMaking an asynchronous GET request.
Makes a GET request without blocking program flow.
Code
<nowiki>
http.request("http://example.com")

while true do
  local event, url, handle = os.pullEvent()

  if event == "http_failure" then
    printError("Failed to make HTTP GET request:")

    -- Here, handle is the error.
    printError(handle)
    break
  elseif event == "http_success" then
    print(handle.readAll())
    handle.close()
    break
  end
end
    </nowiki>
Output Prints the HTML contents of http://example.com.
Functionhttp.websocket
Attempt to establish a WebSocket connection to the given URL.
Syntax http.websocket(
  • url : string
  • headers? : table
)
Returns table handle | nil, string err
Part of CC:Tweaked (source) (source)
API http
See also http.websocketAsync
ExampleCreating a websocket (blocking send/receive)
Connects to ws://demos.kaazing.com/echo (a server that responds with the exact data sent to it).
Code
<nowiki>
local ws, err = http.websocket("ws://demos.kaazing.com/echo")
if not ws then
  return printError(err)
end

ws.send("Hello world!")
local response = ws.receive()
assert(response == "Hello world!", "Received wrong response!")
print(response)

-- Don't forget to close the connection!
ws.close()
    </nowiki>
Output Prints Hello world!
ExampleCreating a websocket (event based)
Connects to ws://demos.kaazing.com/echo, but uses events to receive messages rather than the receive method. This way of receiving events has the advantage that the program is able to respond to other events while waiting for a response, whereas the former method will block on ws.receive().
Code
<nowiki>
local connectionURL = "ws://demos.kaazing.com/echo"
local ws, err = http.websocket(connectionURL)
if not ws then
  return printError(err)
end

ws.send("Hello world!")

while true do
  local _, url, response, isBinary = os.pullEvent("websocket_message")

  -- We need this if statement to check that we received the message from
  -- the correct websocket. After all, you can have many websockets connected to
  -- different URLs.
  if url == connectionURL then
    assert(response == "Hello world!", "Received wrong response!")
    print(response)

    -- Don't forget to close the connection!
    ws.close()

    -- We've received our response and are finished.
    break
  end  
end
    </nowiki>
Output Prints Hello world!

Http.websocketAsync

This article is issued from Computercraft. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.