| request - a request from HttpRequest |
|
Returns 0 while a request runs, then its HTTP status, or a number below 0. Call it each frame to see whether a request has ended. Once it is no longer 0, it stays the same: 0: the request is still running 100 to 599: the server answered, with this HTTP status: 200 means OK, 404 that there is no such page, 500 that the server failed. Every answer counts, even an error page, which you can read with HttpText -1: no answer: no network, no such server, or a certificate the computer doesn't trust -2: the server took too long to answer -4: the answer could not be saved in the request's saveTo$ file -5: the answer was too large to keep in memory: save it to a file instead -6: the address is not one HttpRequest goes to, such as http:// on another computer Below 0, HttpError says why in words, which you can show the player or write to the debug log. Decide what to do from the number, though: the words vary from one computer to another. On the web, a request's end reaches your program while it waits, at Flip, Delay or WaitEvent. See also: HttpRequest, HttpError, HttpText, HttpProgress. |
; 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