HttpRequest ( url$[,method$][,body$][,headers$][,saveTo$][,sendFile$] )

Parameters

url$ - the web address: any https:// address, or an http:// one on this computer (localhost, 127.0.0.1 or [::1])

method$ (optional) - "GET" (default), "POST", "PUT", "DELETE" or another HTTP method, in any case

body$ (optional) - what to send, such as JSON text; "" sends nothing (default)

headers$ (optional) - headers to send, one "Name: value" per line; "" (default)

saveTo$ (optional) - a file to save the answer in, instead of keeping it in memory; "" keeps it in memory (default)

sendFile$ (optional) - a file to send, such as a model or a picture to upload: its bytes are the body, in place of body$; "" sends none (default)

Description

Starts a web request and returns its handle at once.

This is how a game talks to a web server: it fetches a high-score table, posts a new score, checks for news or an update, or downloads a level or a model. HttpRequest only starts the request. It returns straight away, and the answer arrives while your game carries on drawing frames, so the game never freezes while it waits for the network. Check HttpStatus each frame: it is 0 until the request ends, then the server's status, such as 200.

Keep waiting in a loop that calls Flip, Delay or WaitEvent. On the web, the answer can only arrive while your program waits like that, so a loop that just calls HttpStatus until it changes waits forever there.

When it is done, read the answer with HttpText, and turn JSON into data with ParseJson. For a big download, or anything you will keep, such as a model or a level pack, give saveTo$: the answer then goes straight into that file, which appears only once the whole answer is in. A request that fails leaves no file, and an older file of that name stays as it was. HttpProgress tells you how much has arrived, for a progress bar.

To upload a file, such as a level a player made, give its name as sendFile$, with a method such as "PUT" or "POST", and say what it is in headers$, such as "Content-Type: application/octet-stream". The file is read as it goes, so it can be as large as the server accepts, and on Windows HttpProgress counts it going before the answer. Give body$ or sendFile$, not both. A file to send that can't be read ends the request at once, with status -4.

Only https:// addresses are reached, and the computer checks the server's certificate, so a request to a server it doesn't trust ends without an answer. The one exception is http:// on this computer, for trying your game against a server of your own. Any other address ends the request at once, with status -6. Redirects are followed. Each request runs on its own, so you can start several and let them finish in any order.

An answer kept in memory can be up to 64 MB; use saveTo$ for bigger ones. A method that isn't a word, such as "GET me", is an error.

When you are done with a request, free it with FreeHttpRequest, which also stops one that still runs. Requests still running when your program ends are stopped.

On the web, requests go through the browser, which allows only servers that welcome other sites (CORS), and sends no cookies. saveTo$ writes into the program's own files there, and sendFile$ reads from them. On Android, requests use the platform HTTPS transport, with up to four transfers running together and 64 outstanding requests. Downloads replace an existing file only after the complete response arrives. Redirects cannot downgrade HTTPS to HTTP; a redirect to another origin drops caller-supplied headers and refuses to forward an upload. Connection and read operations use 30-second timeouts. Use the persistent SystemProperty("datadir") folder for downloaded files you want to keep.


See also: HttpStatus, HttpText, HttpProgress, FreeHttpRequest, ParseJson.

Example

; HttpRequest Example
; -------------------

Graphics 640,480,0,2
SetBuffer BackBuffer()

; The Khronos Group's list of glTF sample models: a JSON file on GitHub
url$="https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/model-index.json"

; Start the request: HttpRequest returns at once, and the answer
; arrives while the program carries on
request=HttpRequest(url)

; The first 20 model names, once the answer is in
Dim names$(19)
count=0
unread=True

While Not KeyDown(1)

    ; Space asks again
    If KeyHit(57) Then
        FreeHttpRequest request
        request=HttpRequest(url)
        unread=True
        count=0
    EndIf

    ; HttpStatus is 0 while the request runs, then the HTTP status
    status=HttpStatus(request)
    If status=200 And unread Then
        ; The answer is text: here, a JSON array of models
        index=ParseJson(HttpText(request))
        If index Then
            count=JsonCount(index)
            For i=0 To 19
                If i<count Then
                    model=JsonArrayGet(index,i)
                    label=JsonObjectGet(model,"label")
                    names(i)=JsonText(label)
                    FreeJson label
                    FreeJson model
                EndIf
            Next
            FreeJson index
        EndIf
        unread=False
    EndIf

    Cls
    Text 0,0,"Space: ask again   Esc: exit"
    If status=0 Then
        Text 0,20,"Asking GitHub for the glTF sample models..."
    ElseIf status<0 Then
        ; Below 0, the request ended without an answer
        Text 0,20,"No answer: "+HttpError(request)
    Else
        Text 0,20,"HttpStatus: "+status+"   Content-Type: "+HttpHeader(request,"Content-Type")
        Text 0,40,count+" models; the first 20:"
        For i=0 To 19
            Text 20,70+i*20,names(i)
        Next
    EndIf

    ; Waiting a frame lets the answer arrive, on the web too
    Flip

Wend

FreeHttpRequest request
End

Index